DEV Community

Arvind Toorpu
Arvind Toorpu

Posted on

SQL Server Query Store: Catching Plan Regressions Before Users Do

A few months back I got paged because a nightly batch job that normally finished in 12 minutes was still running at hour two. Nothing had changed in the code. No deploy, no schema change, no index rebuild that anyone remembered. What actually happened: an auto-stats update kicked in overnight, the optimizer picked a new plan for one of the core queries, and the new plan was catastrophically worse for that table's data distribution. Same query text, same server, wildly different runtime, and nobody would have known which plan changed or when without a paper trail.

That paper trail is Query Store, and if you're running SQL Server and not turning it on, you're debugging blind.

What it actually is

Query Store is a built-in feature that persists query text, execution plans, and runtime statistics to disk, per database, across time windows. Instead of losing plan history every time the plan cache gets flushed or the instance restarts, you get a queryable history: which plans a query has used, how each one performed, and when the optimizer switched from one to another. It's been enabled by default in Azure SQL Database and Managed Instance for a while, and as of SQL Server 2022 it's on by default for new databases. If you're on 2016 through 2019, or you inherited an older database that predates the default flip, you have to turn it on yourself.

Turning it on and configuring it sanely

ALTER DATABASE [YourDatabase]
SET QUERY_STORE = ON (
    OPERATION_MODE = READ_WRITE,
    MAX_STORAGE_SIZE_MB = 1000,
    QUERY_CAPTURE_MODE = AUTO,
    INTERVAL_LENGTH_MINUTES = 60,
    STALE_QUERY_THRESHOLD_DAYS = 30,
    SIZE_BASED_CLEANUP_MODE = AUTO,
    WAIT_STATS_CAPTURE_MODE = ON
);
Enter fullscreen mode Exit fullscreen mode

Check the current state and confirm it isn't quietly stuck:

SELECT actual_state_desc, desired_state_desc, current_storage_size_mb,
       max_storage_size_mb, readonly_reason, query_capture_mode_desc
FROM sys.database_query_store_options;
Enter fullscreen mode Exit fullscreen mode

QUERY_CAPTURE_MODE = AUTO matters more than people think. ALL captures every ad hoc statement, which on a workload full of non-parameterized queries turns into plan explosion and rapid storage growth. AUTO filters out low-value one-off queries and keeps the store focused on things that actually recur.

Finding regressions

This is the core workflow. You join the query, plan, and runtime stats catalog views to see how a single query's behavior changed across plans over time:

SELECT
    q.query_id,
    qt.query_sql_text,
    p.plan_id,
    p.last_execution_time,
    rs.avg_duration,
    rs.avg_cpu_time,
    rs.avg_logical_io_reads,
    rs.count_executions
FROM sys.query_store_query AS q
JOIN sys.query_store_query_text AS qt ON q.query_text_id = qt.query_text_id
JOIN sys.query_store_plan AS p ON q.query_id = p.query_id
JOIN sys.query_store_runtime_stats AS rs ON p.plan_id = rs.plan_id
WHERE q.query_id = 3
ORDER BY rs.last_execution_time DESC;
Enter fullscreen mode Exit fullscreen mode

If you see multiple plan_id values for the same query_id with meaningfully different avg_duration or avg_logical_io_reads, that's your regression, right there in the data, with timestamps.

SSMS also ships a "Regressed Queries" report under the database's Query Store node that does this visually and lets you compare plan XML side by side, which is worth using before you write ad hoc queries by hand.

Once you've identified the plan that used to be fast, force it:

EXECUTE sp_query_store_force_plan
    @query_id = 3,
    @plan_id = 3;
Enter fullscreen mode Exit fullscreen mode

That pins the optimizer to that specific plan for that query going forward, no code change needed. To release it later:

EXECUTE sp_query_store_unforce_plan
    @query_id = 3,
    @plan_id = 3;
Enter fullscreen mode Exit fullscreen mode

Check on the health of forced plans periodically, because forcing isn't guaranteed to always succeed (stats changes, schema drift, etc. can cause a forced plan to fail to reproduce):

SELECT p.plan_id, p.query_id, p.force_failure_count, p.last_force_failure_reason_desc
FROM sys.query_store_plan AS p
WHERE p.is_forced_plan = 1;
Enter fullscreen mode Exit fullscreen mode

Letting the engine fix it for you

If you'd rather not hand-babysit forced plans, SQL Server's automatic tuning can do the detection and forcing itself:

ALTER DATABASE [YourDatabase]
SET AUTOMATIC_TUNING ( FORCE_LAST_GOOD_PLAN = ON );
Enter fullscreen mode Exit fullscreen mode

With this on, the engine watches for regressions (generally when a new plan is estimated to cost at least 10 seconds more CPU, or throws more errors than the prior plan), forces the last known good plan automatically, and keeps monitoring: if the forced plan doesn't actually perform better, it un-forces it and lets the optimizer try again. It depends entirely on Query Store being enabled, since that's where the plan history it reasons over comes from. I run this in READ_WRITE mode everywhere I can, then use manual forcing surgically for the handful of queries where I don't trust the automatic 10-second CPU threshold to catch a regression that matters at my scale.

Where this requires care

It fills up and goes silently read-only. When current_storage_size_mb hits max_storage_size_mb, Query Store flips to read-only and stops collecting new data. readonly_reason will usually show 65536 (quota exceeded). Nothing crashes, nothing pages you, it just quietly stops recording history exactly when you need it most. Check sys.database_query_store_options on a schedule, not just when something's already on fire.

Non-parameterized queries blow up storage. Ad hoc SQL without parameters generates a new query_id for every literal variation, which floods the plan store. Find the offenders with query_parameterization_type = 0 in sys.query_store_query, and push those callers toward sp_executesql or stored procedures, or turn on "optimize for ad hoc workloads" at the instance level.

Renaming the database or dropping and recreating objects breaks forced plans. Forced plans reference objects by their three-part name and internal IDs. Rename the database, or drop and recreate a stored procedure instead of altering it, and you lose the plan history tied to it. Use ALTER PROCEDURE, not drop-and-recreate, if you want continuity.

INTERVAL_LENGTH_MINUTES trades granularity for storage. A shorter interval gives you finer-grained runtime stats but grows the store faster. On busy OLTP systems, 60 minutes is a reasonable default; drop it lower only while actively investigating something, then put it back.

It's overhead, not free. On very high-throughput, latency-sensitive systems, watch for QUERY_STORE_ASYNC_PERSIST or QDS_CONTROL_ROW_LOCK wait types. Microsoft's shipped several fixes for spinlock contention under heavy ad hoc load in cumulative updates for 2016 through 2019, so if you're seeing Query Store-related waits on an older CU, check whether you're current before assuming it's inherent to the feature.

My take

Query Store is one of the few SQL Server features I'd call close to mandatory rather than optional. Plan regressions are inevitable, stats update, data skews, someone runs a bad ad hoc query that pollutes the cache, and without Query Store you're stuck reconstructing what happened from sys.dm_exec_query_stats, which loses its history the second the plan cache gets evicted. With it, you have an actual timeline to point to when someone asks "what changed." Turn it on everywhere, set QUERY_CAPTURE_MODE = AUTO so you're not drowning in ad hoc noise, and seriously consider FORCE_LAST_GOOD_PLAN automatic tuning as your first line of defense. Manual forcing is for the cases automatic tuning's thresholds don't catch, not your primary tool.

Further reading

Top comments (0)