Hi Geeks,

In my previous blog post we saw how parameter sniffing could negatively impact any query performance when SQL Server query optimizer decides to sniff parameters. There are different ways that helps us to avoid this problem and today I’m going to discuss SQL Server optimize for unknown and local variables.

Local variables

Let me modify our stored procedure from yesterday and introduce a local variable then execute.


One thing to note here is, by using local variables we are disallowing SQL Server to see the value till execution time i.e. it won’t know the values at optimization phase. We are forcing query optimizer not to use statistics objects histogram to find an optimal plan. This solution will use same plan by ignoring parameters supplied during execution time.

OPTMIZE for unknown

Now, let me modify the stored procedure again and introduce sql server optimize for unknown hint then execute the stored procedure using a different parameter.


From the above figure by introducing Optimize for unknown query hint helps SQL Server optimizer to choose a better plan though query statement and parameter seems to be same. It does not sniff parameters anymore and free to choose best possible plan.



Like us on FaceBook | Join the fastest growing SQL Server group on FaceBook | Follow me on Twitter | Follow me on FaceBook