What you will be able to do
- Explain parameter sniffing as plan-cache reuse, not a bug - and the exact condition that makes it hurt.
- Reproduce the failure: same query, different parameter, different plan quality, one cache.
- Choose between OPTIMIZE FOR, RECOMPILE, a Query Store hint, and a plan-guide approach for a real workload.
- State what parameter-sensitive-plan optimisation adds in 2022 and which patterns it covers.
SQL Server compiles a plan once and caches it, so the next execution of the same statement text reuses it. That is the correct default - compilation is expensive. The trouble arrives when the right plan depends on the parameter value, and the cached plan was built around a value that is not the common case. This is parameter sniffing, and it is the single most common reason a query is “fast in SSMS, slow in the application” - SSMS’s ad-hoc text compiled a different plan than the parameterised stored procedure.
The analogy is a timetable written from the first journey of the day. The planner measured the route at dawn, on empty roads, and published that timing for every departure. Every later journey inherits it - correct for the dawn run, badly wrong at rush hour, and nothing about the road is broken. The plan cache does the same: the first caller fixes the plan every later caller executes, which is exactly right until the distributions differ.
The most common mistake is treating the symptom as a server fault - blaming hardware, restarting the instance, or clearing the whole plan cache - when the fingerprint is one statement whose cost differs wildly per parameter value. Clearing the cache appears to fix it until the same first compile happens again, and it is why the diagnostic is the p95/p99 per parameter value, never the average: the problem exists precisely because the average was fine.
Why it happens
At compile time the optimiser sniffs the parameter values in the calling batch and uses the histogram to estimate rows for those specific values. The plan is then cached for the statement, not for the value. Later executions with different values reuse the same plan - a plan that was right for the compile-time value and may be badly wrong for theirs.
How one bad plan poisons every later call
First call
@status = 'rare_value'
Rare value returns few rows - the optimiser picks a seek-and-lookup plan, and caches it
Plan cached
The seek plan, keyed to the statement text
Every later call gets this plan regardless of its own parameter
Common call
@status = 'common_value'
Returns most of the table - a scan would be right, but it reuses the seek plan and does a million lookups
Regression
The p99 on the common value collapses
Nothing is wrong with the query or the data - the plan belongs to a different distribution
The tell-tale shape: estimated rows far from actual rows only for some parameter values, and a plan that is expensive for the common case but cheap for the rare one. Parameter sensitivity matters only when the distribution is skewed - if all values return similar row counts, one plan serves them all and the cache does its job.
The remedies, and what each costs
| Remedy | What it does | When to reach for it | The cost |
|---|---|---|---|
OPTIMIZE FOR (@p = 'common_value') |
Compiles for a value you choose | The common case is stable and known | Hard-codes a value; wrong if the data drifts |
OPTIMIZE FOR UNKNOWN |
Uses density, not the histogram - a generic plan | No single value dominates; you want one safe plan | Gives up on ever getting the ideal plan for selective values |
OPTION (RECOMPILE) |
Recompiles every execution with the actual value | Value distributions differ wildly and recompile cost is small | Pays full compile cost per call - fine on infrequent queries, ruinous on hot ones |
| Local variable copy | Hides the value from the compiler like OPTIMIZE FOR UNKNOWN |
Same as OPTIMIZE FOR UNKNOWN, works everywhere |
Same - the generic plan, never the selective one |
| Query Store hint | Forces a hint or plan without changing code | You cannot deploy a code change | Operational, not a fix for the underlying skew |
| Two procedures / branches | Different SQL text for the two distributions, so two cached plans | The split is binary and known up front | Duplicated code the schema must keep consistent |
The honest trade is between one plan for all (the OPTIMIZE FOR family) and a plan per call
(RECOMPILE). Neither is free: the first sacrifices the ideal case, the second the compile cost.
Choose by how different the distributions are and how often the query runs.
What 2022 changes: parameter-sensitive plan optimisation
SQL Server 2022 (16.x) adds parameter-sensitive-plan (PSP) optimisation, an Intelligent Query Processing feature that automatically keeps multiple plans for one parameterised statement and dispatches by the parameter’s actual distribution - the engine does the two-procedures pattern for you, for eligible predicates on skewed data. It is a genuine fix for the most common sniffing failure, but scoped: it targets specific predicate patterns, and it only exists on 2022 and later with Query Store enabled. On 2019 and earlier, or for predicates outside its scope, the remedies in the table are still the answer.
Diagnosing it in the field
- Two plans in Query Store for one query with wildly different costs is the fingerprint of sensitivity or a recompile cycle - compare their parameter values.
sp_executesqlwith the same text but different plans per parameter set points the same way.- The remedy you pick should be validated by the p95/p99 split per parameter value, not the average - the whole problem is that the average was fine.
Guided practice
A beginner exercise, worked in a scratch database. The scenario: reproduce the lesson’s failure by hand - same query, different parameter, different plan quality, one cache. Work each step and check yourself before moving on.
- Build a skewed table. Create
dbo.ticketswith an id and astatus varchar(20), plus a nonclustered index onstatus. Insert a few thousand rows where nearly all are'common_value'and a small handful are'rare_value'- the skew is the whole point. Check:SELECT status, COUNT(*) FROM dbo.tickets GROUP BY statusshows a lopsided distribution. If the counts are similar, one plan legitimately serves all values and nothing below will hurt - parameter sensitivity only matters when the distribution is skewed. - Wrap the query in a procedure.
CREATE PROCEDURE dbo.get_tickets @status varchar(20) AS SELECT * FROM dbo.tickets WHERE status = @status;- parameterised, so the plan is cached for the statement. Check: the procedure takes a parameter rather than embedding the value. If you ran ad-hoc literals instead, each value compiles its own plan and you cannot reproduce the failure - the cache key is the statement, not the parameter. - Compile with the rare value first. Execute
dbo.get_tickets 'rare_value'with the actual execution plan on and note the operator choice. Check: a seek, probably with a lookup - few rows expected, so the optimiser builds a seek-shaped plan and caches it for the statement. If you got a scan on the rare value, your skew may not be skewed enough; revisit step 1. - Call the common value on the same cache. Execute
dbo.get_tickets 'common_value'without recompiling and compare the plan and its estimated versus actual rows. Check: the same seek-and-lookup plan reused against most of the table - actual rows far above estimated, and a lookup count that is a second query hiding inside the first. That is the regression: nothing about the data is wrong; the plan belongs to a different distribution. - Compare against the per-call plan. Recreate the procedure with
OPTION (RECOMPILE)and run both values again. Check: the rare value still seeks, but the common value now scans - each call compiled for its own sniffed value. If both still share a plan, the hint did not apply; check the syntax against the remedies table. - Choose a remedy and state its cost. For this workload, pick from
OPTIMIZE FOR,OPTIMIZE FOR UNKNOWN,RECOMPILE, or a Query Store hint, and say in one sentence what it charges. Check: any defensible answer names a trade:OPTIMIZE FORhard-codes a value that can drift,UNKNOWNgives up the ideal plan for selective values,RECOMPILEpays compile cost per call - ruinous on hot queries. If you answered “whichever is fastest” without a cost, reread the remedies table - the honest trade is one plan for all versus a plan per call.
Check your understanding
Ordered easy to hard. Answer each before reading the answer; a wrong answer names where to look.
- What does the plan cache key on - the parameter value or the statement? The statement text. The first compile sniffs the parameter values to estimate rows, caches the plan under the statement, and every later call reuses it regardless of its own value - whoever compiles first decides the plan everyone executes.
- Why is parameter sniffing the correct default rather than a bug? Compilation is expensive, and a plan built around the actual compile-time value is usually the best available guess. It only hurts when the distribution is skewed - when all values return similar row counts, one plan serves them all and the cache does its job. If you called it a defect, revisit “why it happens”.
- What is the usual mechanism behind “fast in SSMS, slow in the application”? Two different compilations: SSMS’s ad-hoc text compiled a plan around its literal, while the application’s parameterised stored procedure reused a cached plan built around a different value. Same query, different plan quality, one cache - the field fingerprint is two plans for one statement with wildly different costs. Revisit the flow diagram if this is unclear.
- When is
OPTION (RECOMPILE)the right remedy, and when is it ruinous? When the value distributions differ wildly and the query is infrequent enough that paying full compile cost per call is cheap insurance. On a hot query it pays that cost on every execution - the remedies table exists precisely because neither “one plan for all” nor “a plan per call” is free; choose by how different the distributions are and how often the query runs. - What does parameter-sensitive-plan optimisation add in SQL Server 2022, and what are its limits? It keeps multiple plans for one parameterised statement and dispatches by the parameter’s actual distribution - the engine doing the two-procedures pattern automatically. The limits are scope: eligible predicate patterns only, 2022 and later, and it needs Query Store enabled. On 2019 and earlier the remedies in the table are still the answer - if you presented it as a general fix, reread the version notes.
Where SQL Server sits
How this component relates to the rest of the stack. Items without a link are not covered here yet.
Deployed with
Commonly run alongside
- Windows Failover Clustering