Many of us might have experienced that a query runs perfect for long time then suddenly it started performing very bad with no clues. After lot of investigation, we find that parameter that are supplied by application to run the respective SQL query performs well but sometime because of certain value the plan gets recompiled and same plan is stored in cache resulting poor query performance.
The OPTIMIZE FOR query hint comes into rescue since SQL Server 2005 which allows us to instruct query optimizer to optimize a query execution for the parameter we specify. This can be very useful at different times but may result in bad plan as well if not checked properly. I’ll now demonstrate this with the help of a simple query.
USE [AdventureWorks2012] --Query 1 SELECT * FROM Person.Address WHERE Address.City = 'Bothell' --Query 2 SELECT * FROM Person.Address WHERE Address.City = 'Paris'
From above figure, the second query is slightly expensive than first query as it uses Clustered Index Scan which read through all rows. Let me now run the same set of statements using parameters.
USE [AdventureWorks2012] DECLARE @City VARCHAR(20) SET @City = 'Bothell' SELECT * FROM Person.Address WHERE Address.City = @City SET @City = 'Paris' SELECT * FROM Person.Address WHERE Address.City = @City
Above plan uses Clustered Index Scan for both the queries as it’s not sure about the values till the run time. Now, let me make some modification and include OPTIMIZE FOR query hint for the second query.
USE [AdventureWorks2012] DECLARE @City VARCHAR(20) SET @City = 'Paris' SELECT * FROM Person.Address WHERE Address.City = @City OPTION (OPTIMIZE FOR (@CITY = 'Bothell'))
Paris have very low selectivity as there are many values (around 398) equals to that within the index. The OPTIMIZE FOR hint was able to instruct query optimizer to create plan as same as the one used for Bothell and this helped to improve query performance in our example.
This is an illustration and improper use of any query hints may cause negative impact.