🗄️ Fix Parameter Sniffing on a Seasonal Reporting Query
SQL Server caches a query plan based on the parameter values present the very first time it’s compiled, and a seasonal reporting query (think: ‘orders in the last N days’) that first compiles during a quiet period gets a plan optimized for a tiny row estimate — the same cached plan then gets reused during a high-volume season with a completely different actual row count, and a plan built for ‘small’ performs badly at ‘huge’ because the optimizer never got a chance to reconsider.
🔎 The Problem
CREATE PROCEDURE rpt.GetOrdersInRange @Days INT AS BEGIN SELECT * FROM Orders WHERE OrderDate >= DATEADD(day, -@Days, GETDATE()); END -- First compiled with @Days = 7 (quiet period, ~400 rows) -- plan uses a Key Lookup per row - fine at 400 rows, -- catastrophic when reused during a @Days = 90 holiday report (800k rows)
✅ Fix: Give the Optimizer a Plan That Fits the Actual Range Size
- Add
OPTION (RECOMPILE)to the specific statement if it’s run infrequently enough that recompiling every execution is cheaper than risking a badly-fitted cached plan. - For a query run often enough that recompiling every time is wasteful, use
OPTION (OPTIMIZE FOR (@Days UNKNOWN))to get a plan based on average distribution statistics instead of whatever happened to compile first. - Split genuinely different-shaped workloads (a ‘recent orders’ dashboard vs. a ‘full season’ report) into separate stored procedures so each gets its own cached plan tuned to its own typical row count.
The plan isn’t wrong for the data it was compiled against — it’s wrong for the data that showed up six months later.



