// SQL snippet

Find plan regressions with Query Store in SQL Server

Query Store remembers what each query used to cost, so "it got slower last week" becomes a number you can check.

Main statement
SQL Server

The task

Query Store (SQL Server 2016+) persists per-query runtime statistics in the database itself, surviving restarts and plan evictions. Comparing recent runtime stats against historical ones per query_id finds exactly the shape of a plan regression: the same query, suddenly slower than its own history, usually right after a plan change or statistics update.

The snippet

Written for SQL Server.

SQL Server
WITH stats AS (
    SELECT p.query_id,
           CASE WHEN rs.last_execution_time >= DATEADD(DAY, -1, SYSUTCDATETIME()) THEN 'recent' ELSE 'historic' END AS period,
           rs.avg_duration * rs.count_executions AS total_us,
           rs.count_executions
    FROM sys.query_store_runtime_stats rs
    JOIN sys.query_store_plan p ON p.plan_id = rs.plan_id
    WHERE rs.last_execution_time >= DATEADD(DAY, -30, SYSUTCDATETIME())
), agg AS (
    SELECT query_id,
           SUM(CASE WHEN period = 'recent' THEN total_us END)
             / NULLIF(SUM(CASE WHEN period = 'recent' THEN count_executions END), 0) / 1000.0 AS after_ms,
           SUM(CASE WHEN period = 'historic' THEN total_us END)
             / NULLIF(SUM(CASE WHEN period = 'historic' THEN count_executions END), 0) / 1000.0 AS before_ms,
           SUM(CASE WHEN period = 'recent' THEN count_executions END) AS recent_executions
    FROM stats
    GROUP BY query_id
)
SELECT a.query_id, a.recent_executions,
       CAST(a.before_ms AS DECIMAL(12,2)) AS before_ms,
       CAST(a.after_ms AS DECIMAL(12,2)) AS after_ms,
       CAST(a.after_ms / NULLIF(a.before_ms, 0) AS DECIMAL(10,2)) AS slowdown_factor,
       LEFT(qt.query_sql_text, 120) AS query
FROM agg a
JOIN sys.query_store_query q ON q.query_id = a.query_id
JOIN sys.query_store_query_text qt ON qt.query_text_id = q.query_text_id
WHERE a.after_ms > a.before_ms * 2
ORDER BY slowdown_factor DESC;

Como funciona

Query Store keeps one row per query in sys.query_store_query, one or more plans per query in sys.query_store_plan, and runtime statistics per plan per time interval (one hour by default) in sys.query_store_runtime_stats, with durations in microseconds. The query splits the last 30 days at 24 hours ago, then computes an execution-weighted average for each side: avg_duration times count_executions, summed and divided by total executions, so an interval with one run does not count as much as one with ten thousand. A slowdown_factor above 2 flags a candidate. The variant lists that query's plans; a new plan_id that dominates the recent intervals confirms a plan regression, and sp_query_store_force_plan pins the old plan while you find the cause.

Variations

Show the plans behind one regressed query

DECLARE @query_id BIGINT = 42;  -- from the main query

SELECT p.plan_id, p.is_forced_plan,
       SUM(rs.count_executions) AS executions,
       CAST(SUM(rs.avg_duration * rs.count_executions) / NULLIF(SUM(rs.count_executions), 0) / 1000.0 AS DECIMAL(12,2)) AS avg_ms,
       MIN(rs.first_execution_time) AS first_seen,
       MAX(rs.last_execution_time) AS last_seen
FROM sys.query_store_plan p
JOIN sys.query_store_runtime_stats rs ON rs.plan_id = p.plan_id
WHERE p.query_id = @query_id
GROUP BY p.plan_id, p.is_forced_plan
ORDER BY last_seen DESC;

Questions that come up

Is Query Store on by default?

It is on by default for new databases from SQL Server 2022 onward and in Azure SQL Database. On SQL Server 2016 to 2019 it is off unless someone enabled it, and a database upgraded or restored onto a newer version keeps its old setting. Check actual_state_desc in sys.database_query_store_options; READ_ONLY usually means it ran out of its size quota. Enable it with ALTER DATABASE CURRENT SET QUERY_STORE = ON (OPERATION_MODE = READ_WRITE).

Should I force a plan as a fix?

As a first step, often yes: EXEC sp_query_store_force_plan @query_id = 42, @plan_id = 7 restores the old plan immediately while you work out why the optimizer switched (new statistics, a plan compiled for an unusual parameter value, data growth). The forced plan can become the wrong plan as data changes, and forcing fails if an index it uses is dropped (check force_failure_count in sys.query_store_plan), so review forced plans periodically. SQL Server 2017 and later can also do this automatically with automatic plan correction (FORCE_LAST_GOOD_PLAN).

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.