SQL Server optimize for unknown and local variables

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.

--USE [AdventureWorks2012]

-- Step 1
ALTER PROCEDURE sp_RetPurOrdDetail (@PID INT)
AS
DECLARE @PR INT = @PID
SELECT * FROM [Purchasing].[PurchaseOrderDetail]
WHERE PurchaseOrderDetail.ProductID = @PID

--Step 2
EXEC sp_RetPurOrdDetail @PID=876

LocalVarGrphPlan

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.

--USE [AdventureWorks2012]

-- Step 1
ALTER PROCEDURE sp_RetPurOrdDetail (@PID INT)
AS
SELECT * FROM [Purchasing].[PurchaseOrderDetail]
WHERE PurchaseOrderDetail.ProductID = @PID
OPTION (OPTIMIZE FOR UNKNOWN)

--Step 2
EXEC sp_RetPurOrdDetail @PID=319

OptimizedGrphPlan

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.

Regards,

Kanchan

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

   

About Kanchan Bhattacharyya

Kanchan is an astute IT professional, a seasoned SQL Database Administrator with 13+ years of industry experience. A calculated risk taker with deep technical knowledge and has gained proficiency in database consulting and solutions across different environments. Kanchan holds MBA degree in IT and an International Executive MBA in Project Management. He is very passionate about SQL Server and holds MCSE (Data Platform), MCSA – SQL 2012, MCITP – SQL 2008 certifications. Currently he is focusing on cloud and latest releases of SQL Server. When not working, Kanchan likes to spend his time reading on new technical developments specifically on SQL Server and other related technologies.

View all posts by Kanchan Bhattacharyya →

Leave a Reply

Your email address will not be published.