SQL Server Query Store: How It Works and How to Force a Better Plan

SQL Server Query Store: How It Works and How to Force a Better Plan

The plan cache (Module 1) resets on restart and only shows current state. Query Store persists query and plan performance history per database, across restarts — and lets you directly force a known-good plan.

Catch the regression, force the fix(a plan’s history, sketched)Plan Aavg duration: 12msthe GOOD planrunning happily for weeks!Plan Bavg duration: 850msREGRESSED after recompilenew parameter, bad estimatePlan Anow FORCED (pinned)sp_query_store_force_planno code deploy neededrecompile — new paramforce_plan pins itQuery Store remembers every plan ever compiled for a query —you look up the good one and pin it, instead of guessing.Gotcha: forcing a plan isn’t forever. If it becomesinvalid (e.g. an index it needs gets dropped), SQL Serversilently falls back to a fresh compile — checklast_force_failure_reason, don’t assume it’s permanent. 📌

Enabling It

ALTER DATABASE YourDatabase SET QUERY_STORE = ON;
ALTER DATABASE YourDatabase SET QUERY_STORE (OPERATION_MODE = READ_WRITE);

Finding Regressed Queries

SELECT q.query_id, qt.query_sql_text, rs.avg_duration, rs.last_execution_time
FROM sys.query_store_query q
JOIN sys.query_store_query_text qt ON q.query_text_id = qt.query_text_id
JOIN sys.query_store_plan p ON q.query_id = p.query_id
JOIN sys.query_store_runtime_stats rs ON p.plan_id = rs.plan_id
ORDER BY rs.avg_duration DESC;

The Feature That Directly Fixes Parameter Sniffing: Forcing a Plan

Query Store remembers every plan a query has ever used You can pin the good one, permanently, without changing code

EXEC sp_query_store_force_plan @query_id = 42, @plan_id = 137;
-- Later, to release it:
EXEC sp_query_store_unforce_plan @query_id = 42, @plan_id = 137;

This is a genuinely production-safe response to the Module 3 parameter sniffing problem — no code deployment needed, immediately reversible, and the exact plan is verifiable (unlike a hint that only influences future compilation).


Enjoyed this?

Subscribe to get every new lesson as soon as it’s published, and share it with a developer who’d find it useful.

📡 Subscribe via RSS  | 
Share on X  | 
Share on LinkedIn  | 
Share on Facebook

Want the full structured course with quizzes and hands-on labs? Check out SQL Server Performance Tuning, coming soon on this site.