T-SQL query performance puzzle: Why does using a variable make a difference?

て烟熏妆下的殇ゞ 提交于 2019-11-30 17:44:40

The cause might be that IsNull(sv.InstanceID,1) = @InstanceID is very selective for some values of @InstanceID, but not very selective for others. For example, there could be millions of rows with InstanceID = null, so for @InstanceID = 1 a scan might be quicker.

But if you explicitly provide the value of @InstanceID, SQL Server knows based on the table statistics whether it's selective or not.

First, make sure your statistics are up to date:

UPDATE STATISTICS table_or_indexed_view_name 

Then, if the problem still occurs, compare the query execution plan for both methods. You can then enforce the fastest method using query hints.

With hardcoded values the optimizer knows what to base on when building execution plan. When you use variables it tries to "guess" the value and in many cases it gets not the best one.

You can help it to pick a value for optimization in 2 ways:

  1. "I know better", this will force it to use the value you provide.

    OPTION (OPTIMIZE FOR(@InstanceID=1))

  2. "See what I do", this will instruct it to sniff the values you pass and use average (or most popular for some data types) value of those supplied over time.

    OPTION (OPTIMIZE FOR UNKNOWN)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!