A customer contacted me with the following problem:
“We notice vastly different timings when executing the same query over time. Every time we change something small to the structure of the query, the performance is OK again (for a while). ”
This immediately ringed a bell and I expected that there was a problem with the execution plan. And indeed this was confirmed when looking at some of the queries:
Why is this happening?
This is an example of parameter sniffing. The first time a query is ran on SQL server, SQL will generate an execution plan for it and store that plan in the query plan cache. All subsequent executions of that same query will go to the query cache to reuse that same initial query plan — this saves SQL Server time from having to regenerate a new query plan. The problem is that this can lead to a suboptimal plan when there is big variation in the data.
How do I prevent parameter sniffing?
One option you have is to execute the query with the ‘WITH RECOMPILE’ query hint. This forces SQL Server to generate a new execution plan every time these queries run. The disadvantage here is that we lose all benefit from having SQL Server save CPU cycles by caching execution plans.
Another option is to use the ‘OPTIMIZE FOR’ query hint. You can either choose optimize for ‘UNKNOWN’ or optimize for ‘VALUE’:
- OPTIMIZE FOR UNKNOWN will use a query plan that’s generated from the average distribution stats for that column/index.
- OPTIMIZE FOR VALUE creates a plan using whatever parameter value specified. This is great if you know your queries will be retrieving data that’s optimized for the value you specified most of the time.