What Is SQL Server Parameter Sniffing? Why Can the Same Query Be Fast Sometimes and Extremely Slow at Other Times?

What Is SQL Server Parameter Sniffing? Why Can the Same Query Be Fast Sometimes and Extremely Slow at Other Times?

Why can the same SQL query be fast one moment and extremely slow the next?

One of the most confusing SQL Server performance problems occurs when the same stored procedure runs in milliseconds for one parameter but takes several seconds or even minutes for another.

One possible cause is Parameter Sniffing.

In simple terms:

When SQL Server compiles a parameterized query, it can use the current parameter value to create an execution plan and cache that plan for later executions.

A plan that works perfectly for one parameter may perform very poorly for another.

Understanding execution plan caching

SQL Server does not necessarily optimize every query from scratch on every execution.

Execution plans can be stored in the plan cache and reused later, reducing compilation overhead.

Query ↓ Cached plan available? ↓ Yes ↓ Reuse execution plan ↓ Execute query 

How does Parameter Sniffing happen?

Consider a stored procedure:

CREATE PROCEDURE GetCustomerOrders @CustomerId INT AS BEGIN SELECT Id, CustomerId, OrderDate, TotalAmount, Status FROM Orders WHERE CustomerId = @CustomerId; END 

Suppose the data distribution looks like this:

CustomerId Orders ------------------------ 1 850,000 2 4 3 7 4 2 5 12 

If the procedure is first compiled using CustomerId 5, SQL Server may choose a plan optimized for retrieving only a few rows.

That same cached plan can later be reused for CustomerId 1, which needs to return hundreds of thousands of rows.

The opposite scenario is also possible: a plan optimized for a very large customer may be unnecessarily expensive for customers with only a few rows.

Parameter Sniffing itself is not necessarily a bug

Using parameter values during optimization is normally useful. It allows the optimizer to build a plan based on the expected amount of data.

Problems typically appear when:

  • Data distribution is highly uneven.
  • Different parameter values return dramatically different numbers of rows.
  • One execution plan is not suitable for every parameter.

Common symptoms

  • A stored procedure is sometimes fast and sometimes slow.
  • Performance changes after SQL Server restarts.
  • Recompiling temporarily improves performance.
  • Clearing a cached plan changes query behavior.
  • Different parameters produce dramatically different execution times.

Compare Estimated Rows and Actual Rows

Execution plans can reveal significant cardinality estimation differences.

Estimated Rows : 10 Actual Rows : 850,000 

A large difference can indicate a cardinality estimation problem, although Parameter Sniffing is only one possible cause.

Solution 1: OPTION (RECOMPILE)

SELECT * FROM Orders WHERE CustomerId = @CustomerId OPTION (RECOMPILE); 

RECOMPILE allows SQL Server to generate a new execution plan based on the current parameter.

This can be very effective for queries where parameter values produce dramatically different workloads.

The tradeoff is additional compilation CPU cost.

Solution 2: OPTIMIZE FOR UNKNOWN

SELECT * FROM Orders WHERE CustomerId = @CustomerId OPTION (OPTIMIZE FOR UNKNOWN); 

This asks the optimizer to use a more general estimate instead of optimizing specifically for the current parameter value.

It can provide a more stable middle-ground plan, but the resulting plan may not be ideal for every parameter.

Solution 3: OPTIMIZE FOR a specific value

SELECT * FROM Orders WHERE CustomerId = @CustomerId OPTION (OPTIMIZE FOR (@CustomerId = 100)); 

This can be useful when a representative value is known, but the choice may become outdated as data distribution changes.

SQL Server 2022: Parameter Sensitive Plan Optimization

SQL Server 2022 introduced Parameter Sensitive Plan Optimization — PSP to address cases where one cached plan cannot efficiently serve all parameter values.

Instead of:

Parameterized Query ↓ One Cached Plan ↓ Every Parameter 

eligible queries can use multiple plan variants:

Parameterized Query ↓ Dispatcher Plan ↓ ┌──────────────┬──────────────┬──────────────┐ │ Small Values │ Medium Values│ Large Values │ │ Plan A │ Plan B │ Plan C │ └──────────────┴──────────────┴──────────────┘ 

For SQL Server 2022, PSP requires database compatibility level 160.

SQL Server 2025 expands PSP

SQL Server 2025 with compatibility level 170 expands Parameter Sensitive Plan Optimization to additional scenarios, including supported DML statements such as INSERT, UPDATE, DELETE and MERGE.

PSP still does not mean every parameter-sensitive query automatically receives multiple plans. Eligibility conditions continue to apply.

Query Store is extremely useful

Query Store can help identify when a query changed plans and when performance regressed.

For example:

Yesterday: Query → Plan A → 80 ms Today: Query → Plan B → 14 seconds 

This historical information is extremely useful when investigating intermittent performance problems.

Statistics and indexes still matter

Parameter-sensitive behavior should never be investigated in isolation.

Also review:

  • Statistics freshness
  • Cardinality estimates
  • Indexes
  • Key Lookups
  • Logical reads
  • Execution plan operators

Can Parameter Sniffing be disabled?

Yes, at database scope:

ALTER DATABASE SCOPED CONFIGURATION SET PARAMETER_SNIFFING = OFF; 

However, disabling it globally should not be treated as a general performance fix. Parameter Sniffing is beneficial for many queries.

A targeted query-level hint can also be used:

SELECT * FROM Orders WHERE CustomerId = @CustomerId OPTION (USE HINT('DISABLE_PARAMETER_SNIFFING')); 

Clearing the plan cache is not a permanent solution

Removing a cached plan may temporarily improve performance because the query is recompiled.

But if an unrepresentative parameter causes the next compilation, the same problem can return.

Globally clearing the plan cache in production can also trigger widespread recompilation and additional CPU usage.

A multi-tenant example

Parameter sensitivity is especially relevant in multi-tenant applications:

SELECT * FROM Orders WHERE TenantId = @TenantId AND OrderDate >= @StartDate; 

Imagine this distribution:

Tenant 1 → 5,000,000 orders Tenant 2 → 800 orders Tenant 3 → 120 orders Tenant 4 → 45 orders 

An execution plan that is excellent for Tenant 4 may be completely inappropriate for Tenant 1.

Recommended troubleshooting process

  1. Test the query with different parameter values.
  2. Compare actual execution plans.
  3. Compare estimated and actual row counts.
  4. Review data distribution.
  5. Review statistics.
  6. Inspect Query Store history.
  7. Check index design.
  8. Determine whether one plan can reasonably serve all parameter ranges.
  9. Choose the most targeted solution.

Conclusion

SQL Server Parameter Sniffing can cause intermittent performance problems that are difficult to diagnose because nothing in the SQL text itself appears to change.

When the same stored procedure is sometimes extremely fast and sometimes unexpectedly slow, the important question is:

“For which parameter was this execution plan compiled, and for which parameter is it being reused now?”

Understanding that relationship between parameter values, data distribution and execution plan reuse is often the key to solving the problem correctly.

//

0 Comments

Write Comment

E-Mail address will not be published