الانتقال إلى المحتوى
قواعد البياناتSQL Server· 7 دقائق للقراءة

Same Query, Different Speed: Parameter Sniffing and Plan Reuse in SQL Server

A cached plan is built for the values of one call and reused for all of them. On skewed data, who calls first decides how fast everyone else runs.

ReadIn

مقال كل يوم يفرق معاك

22 نوفمبر 2026
  • كاتب موثّق
  • SQL Server 2025
محتويات المقال

The customer orders page is fast for weeks. Then, after a statistics update, it's slow for nearly everyone, and nobody deployed anything. In a test on SQL Server 2022 at compatibility level 150, the cached plan for that page was compiled during a call for a marketplace account with 200,035 orders: a parallel scan of the whole table and a sort. Every later call reused it. A customer with 48 orders then read 50,914 pages and used 198 to 261 ms of CPU per call, instead of 159 reads and at most 3 ms with a plan compiled for their own value.

The common misconception

The belief: a cached plan that's fast for one parameter value will be fast for every value. Same query, same plan, same speed.

Plan reuse deserves its good reputation. Compiling costs CPU, so Microsoft's guidance is to send parameters instead of literals so the engine can match a statement to its cached plan, and parameterized queries also close the door on SQL injection. Developers test with typical values, and typical values get the typical plan. What nobody sees is which value the plan was built for: the plan doesn't change, so the cost shouldn't either.

What actually happens

Sniffed once, reused for everyone

Microsoft calls it , or parameter sensitivity: during compilation or recompilation, the engine sniffs the current parameter values and passes them to the optimizer. That applies to stored procedures, queries sent through sp_executesql, and prepared queries. The optimizer looks those values up in the statistics, picks the best plan for them, and caches it. The next call with any other value skips compilation and runs the same plan.

Skewed data makes one plan wrong for others

In the test, dbo.Orders held 1,040,000 orders. Customer 42 had 200,035 of them, customer 4242 had 48. The histogram knew it: compiled for 42, the estimate was exactly 200,035 rows. Compiled for 42, the best plan was a parallel scan plus a sort with a 62 MB . Compiled for 4242, it was an index seek plus 48 key lookups. Run each with the other's plan:

Compatibility level 150, plan compiled forThen called forPlanReadsCPU per call
Customer 4242 (48 orders)4242Seek + 48 lookups1590–3 ms
Customer 42 (200,035 orders)4242Parallel scan + sort50,914198–261 ms
Customer 4242Parallel scan + sort50,914670–764 ms
Customer 424242Seek + 200,035 lookups613,677316–354 ms

The last row is the quiet direction: twelve times the page reads, and with every page already in memory, it didn't even use more CPU in the test. That's how a plan can be wrong for weeks before anyone notices.

Whoever calls first decides

A plan is compiled whenever there's none in the cache: after a restart, an eviction, a schema change, or an update to the statistics it uses, which Microsoft's guide lists among the reasons for recompilation. Whichever value arrives next becomes the plan for everyone. That's why the symptom looks random: the same query is fast on Monday and slow on Tuesday.

SQL Server 2022 and 2025 keep more than one plan

At compatibility level 160, SQL Server 2022 adds parameter sensitive plan (PSP) optimization: for equality predicates on skewed columns, it caches a dispatcher plan that routes each call to one of up to three query variants by expected row count. It doesn't engage for every skew. In the test it first reported SkewnessThresholdNotMet, and kicked in only after 20,000 single-order customers widened the gap. Then customer 4242 got its own variant (159 reads) and customer 42 another (50,914), whichever came first. SQL Server 2025 at compatibility level 170 adds optional parameter plan optimization for @p IS NULL OR column = @p filters, and lets PSP pick several predicates from one table. Those 2025 behaviors are described here from Microsoft's docs only; the runs were on SQL Server 2022.

Fix the query, not the cache

SQL
CREATE OR ALTER PROCEDURE dbo.GetCustomerOrders @customerId intASSELECT Id, CreatedAt, Status, Total, EmailFROM dbo.OrdersWHERE CustomerId = @customerIdORDER BY CreatedAt DESC;-- Compiled for customer 42, reused for 4242:-- 50,914 reads and ~200 ms of CPU for 48 rows

With the index covering the query, the seek plan was the best plan for both customers, so it no longer mattered who came first. When no index can do that, the next cheapest fix depends on the query shape. Optional filters are the classic case:

SQL search_orders.sql
SELECT Id, CreatedAt, Status, TotalFROM dbo.OrdersWHERE (@customerId IS NULL OR CustomerId = @customerId)  AND (@status IS NULL OR Status = @status)OPTION (RECOMPILE);-- SQL Server 2022, customer 4242: 11,577 reads without RECOMPILE, 3 with it

Without the hint, one cached plan has to be valid when @customerId is null, so it scanned the whole index. With RECOMPILE, the optimizer turns the parameters into constants and simplifies the filter. Microsoft warns that compiling on every execution can cost a lot, which is what optional parameter plan optimization avoids in SQL Server 2025.

FixWhat it doesTrade-off
An index that suits every valueOne plan stays good for all callersWrite cost and size, like any index
OPTION (RECOMPILE)Compiles for the actual values on every callCPU for every compilation
OPTIMIZE FOR UNKNOWNPlans for the average valueTested: customer 42 got the seek plan, 613,677 reads
PSP (2022, level 160)Up to three plans by row countEquality predicates only; skips mild skew
Optional parameter plan optimization (2025, level 170)Separate plans for null and non-nullNot for local variables or RECOMPILE queries

How to apply it in your project

  1. Find queries with unstable performanceIn Query Store, look for queries with several plans or a wide spread of durations, and check the regressed queries report after statistics updates or restarts.
  2. Compare compiled and runtime valuesGet the actual plan of a slow execution and read ParameterCompiledValue against ParameterRuntimeValue. Count rows per value of the filtered column to confirm the skew.
  3. Make one plan fit, or fit the plan per callTry an index that makes the same plan good for all values first. Otherwise, use OPTION (RECOMPILE) on that statement, or a Query Store hint when you can't change the code.
  4. Plan the compatibility levelPSP needs level 160 on SQL Server 2022, and optional parameter plan optimization needs level 170 on SQL Server 2025. Capture a Query Store baseline before you raise the level, and compare after.

Key takeaways

  • A cached plan is compiled for the values of one call and reused for all values.
  • On skewed data, the wrong plan cost a 48-order customer 50,914 reads and about 200 ms of CPU instead of 159 reads and at most 3 ms in the test.
  • Which plan you get depends on who calls first after a recompile, so the slowdown looks random.
  • SQL Server 2022's PSP keeps up to three plans for skewed equality filters; SQL Server 2025 adds plans per null state for optional filters.
  • Prefer an index that makes one plan good for everyone, then targeted RECOMPILE or hints, never local variables.

📚 المصادر

  1. Query Processing Architecture Guide — SQL Server, Microsoft Learn
  2. Parameter Sensitive Plan Optimization — SQL Server, Microsoft Learn
  3. Optional Parameter Plan Optimization — SQL Server 2025, Microsoft Learn

التعليقات (0)