Covers Query Store: captured query text, plans, runtime and wait statistics per interval, built-in reports, finding regressions, plan forcing and its failure modes, Query Store hints, key settings (capture mode, size, interval, cleanup, READ_ONLY flip) and Azure SQL defaults including automatic plan correction.
Query Store is a flight recorder inside each database. It saves query text, every plan a query has used, and runtime statistics (duration, CPU, logical reads, memory, waits) aggregated per time interval, and it survives restarts and failovers.
I use the Regressed Queries and Top Resource Consuming reports to see which query got slower and whether its plan changed. If it did, I can force the previous plan, or attach a Query Store hint without touching code.
It's on by default in Azure SQL Database and for new databases in SQL Server 2022, and Azure SQL's automatic plan correction can force the last good plan for you. The trade-off is a little overhead and storage; the settings to watch are size, capture mode and the flip to read-only when full.
"Before Query Store, plan cache DMVs were all we had, and they forget everything on restart, failover or eviction, and only keep the current plan. Query Store fixes that. It writes to the user database the text of each query, every plan it has used, and runtime statistics aggregated per interval, an hour by default: execution count, duration, CPU, logical and physical reads, memory grant, row counts, and since 2017 wait categories. Because it's in the database, it survives failovers and goes with the database when you restore it.
I use it in three ways. First, regressions: the Regressed Queries report compares a recent window with a baseline, and if a query has a new plan that's slower I can force the old one with
sp_query_store_force_plan. That's a reversible, visible mitigation during an incident. Second, finding the biggest consumers by total CPU or reads, which is where tuning effort pays off. Third, releases and upgrades: I compare before and after windows, and when raising the compatibility level I keep the old level for a while to capture a baseline, then switch and force any regressions. Since SQL Server 2022 and in Azure SQL there are Query Store hints, so I can attachOPTION (RECOMPILE)orMAXDOP 1to an EF Core query by query_id without a deployment.In Azure SQL Database it's on by default, and automatic plan correction (
FORCE_LAST_GOOD_PLAN) is on by default for new servers, which detects plan regressions, forces the last good plan and verifies it helped. The mistake I see is forgetting it can fill up: when it reaches its size limit it flips to READ_ONLY and silently stops collecting. Query Store is the first place I look, so I make sure it's actually recording."
| Catalog view | Contents |
|---|---|
sys.query_store_query_text / sys.query_store_query |
Text, query_hash, context settings |
sys.query_store_plan |
Each plan, forced flag, force failures, compiled parameter values in the XML |
sys.query_store_runtime_stats |
Per plan per interval: count, avg/min/max/stdev of duration, CPU, reads, memory, rows |
sys.query_store_wait_stats |
Waits per plan per interval by category |
sys.query_store_query_hints |
Hints attached with sp_query_store_set_hints |
| Setting | Default (SQL Server 2022) | What I check |
|---|---|---|
OPERATION_MODE |
READ_WRITE | actual_state_desc is still READ_WRITE |
QUERY_CAPTURE_MODE |
AUTO (skips trivial, infrequent queries) | ALL only for short investigations |
MAX_STORAGE_SIZE_MB |
1,000 | Usage vs limit |
INTERVAL_LENGTH_MINUTES |
60 | Shorter (15) for faster incident detail |
STALE_QUERY_THRESHOLD_DAYS |
30 | Long enough for monthly jobs |
SIZE_BASED_CLEANUP_MODE |
AUTO | Keep on |
After a release, Azure SQL CPU went from [35%] to [90%]. Query Store's Top Resource Consuming report ranked one query first by total CPU; it had a new plan using a parallel scan. Forcing the old plan took CPU back to [40%] in minutes, and the root cause (a LINQ change that dropped a filter on an indexed column) was fixed in the next deployment.
Checks whether the candidate uses Query Store as the primary production performance tool and understands its limits.
Green flags
Red flags
query compiles/executes
|
v
[in-memory Query Store buffers] --async flush (DATA_FLUSH_INTERVAL_SECONDS, default 900)--> [user database tables]
|
v
runtime stats aggregated per plan per interval (INTERVAL_LENGTH_MINUTES)
Collection is asynchronous, so overhead is typically low single-digit percent CPU. A crash can lose the last unflushed minutes of statistics.
A query is identified by its text and context settings (SET options, schema). Each distinct plan gets a plan_id. With PSP optimisation (2022), one parent query has a dispatcher plan and up to three variant queries, which appear as separate query_ids linked by sys.query_store_query_variant.
Forcing stores the plan's shape; at the next compile the optimiser is asked to produce that shape. It can fail if an index the plan used is dropped or renamed (last_force_failure_reason_desc, e.g. NO_INDEX), and then the query compiles normally. SQL Server 2022 adds optimised plan forcing, which stores a replay script to reduce compile time for forced plans.
FORCE_LAST_GOOD_PLAN watches for plan-choice regressions (a new plan with significantly worse CPU), forces the previous plan, then verifies it actually helped and unforces it if not. Recommendations are in sys.dm_db_tuning_recommendations. It is on by default for new Azure SQL Database servers; on SQL Server it must be enabled per database (Enterprise edition feature).
sys.sp_query_store_set_hints @query_id, N'OPTION (...)' applies hints like RECOMPILE, MAXDOP, USE HINT('...'), OPTIMIZE FOR UNKNOWN to a query without changing its text. Ideal for ORM-generated or vendor SQL. Remove with sp_query_store_clear_hints.
MAX_STORAGE_SIZE_MB is reached; check readonly_reason.SELECT actual_state_desc, current_storage_size_mb, max_storage_size_mb FROM sys.database_query_store_options;.sp_query_store_force_plan, drop the index it uses, and read last_force_failure_reason_desc.OPTION (MAXDOP 1) to a query with sp_query_store_set_hints and confirm with the plan's degree of parallelism.sys.dm_db_tuning_recommendations and sys.database_automatic_tuning_options.Health check, top consumers, and forcing.
-- Is Query Store actually recording?
SELECT actual_state_desc, readonly_reason, current_storage_size_mb,
max_storage_size_mb, query_capture_mode_desc, interval_length_minutes
FROM sys.database_query_store_options;
-- Top 10 queries by total CPU in the last 24 hours
SELECT TOP (10)
q.query_id,
SUM(rs.count_executions) AS executions,
SUM(rs.avg_cpu_time * rs.count_executions) / 1000000.0 AS total_cpu_s,
SUM(rs.avg_logical_io_reads * rs.count_executions) AS total_reads,
COUNT(DISTINCT p.plan_id) AS plans,
MIN(qt.query_sql_text) AS query_text
FROM sys.query_store_runtime_stats rs
JOIN sys.query_store_runtime_stats_interval i ON i.runtime_stats_interval_id = rs.runtime_stats_interval_id
JOIN sys.query_store_plan p ON p.plan_id = rs.plan_id
JOIN sys.query_store_query q ON q.query_id = p.query_id
JOIN sys.query_store_query_text qt ON qt.query_text_id = q.query_text_id
WHERE i.start_time > DATEADD(hour, -24, SYSUTCDATETIME())
GROUP BY q.query_id
ORDER BY total_cpu_s DESC;
-- Force the good plan, and later check it is still being honoured
EXEC sys.sp_query_store_force_plan @query_id = 1234, @plan_id = 56;
SELECT plan_id, is_forced_plan, force_failure_count, last_force_failure_reason_desc
FROM sys.query_store_plan WHERE query_id = 1234;
-- Sensible settings for a busy OLTP database
ALTER DATABASE CURRENT SET QUERY_STORE = ON
(OPERATION_MODE = READ_WRITE, QUERY_CAPTURE_MODE = AUTO,
MAX_STORAGE_SIZE_MB = 4096, INTERVAL_LENGTH_MINUTES = 15,
SIZE_BASED_CLEANUP_MODE = AUTO);
Tag EF Core queries so they're easy to find in query_sql_text:
namespace Shop.Data;
using Microsoft.EntityFrameworkCore;
public sealed class DashboardQueries(ShopDbContext db)
{
public Task<decimal> RevenueSinceAsync(DateTime from, CancellationToken ct) =>
db.Orders
.TagWith("dashboard:revenue-since") // appears as a SQL comment in Query Store
.Where(o => o.OrderDate >= from)
.SumAsync(o => o.Total, ct);
}
actual_state_desc and on usage above about 80% of MAX_STORAGE_SIZE_MB; raise the limit and keep size-based cleanup on.ALTER DATABASE ... SET QUERY_STORE = ON (OPERATION_MODE = READ_WRITE) and verify settings, ideally before changing compatibility level so you have a baseline.force_failure_count and last_force_failure_reason_desc, and unforce once the root cause is fixed.sys.dm_db_tuning_recommendations.Query Store turns 'it was slow yesterday' from guesswork into data, and it should be part of every release and upgrade process: capture, compare, mitigate, fix. The senior habits are making sure it's healthy (size, mode, interval), owning the list of forced plans and hints as operational state, and preferring code fixes once the fire is out.
In Azure SQL Database it's on by default with automatic plan correction on new servers; on SQL Server 2022 it's on for new databases, but upgraded databases may still have it off, so check.
| Mitigation | When it fits | Cost | When not to |
|---|---|---|---|
| Force last good plan | Clear plan-choice regression | Plan may age badly | Regression from data growth, not plan change |
| Query Store hint | ORM/vendor SQL needing RECOMPILE, MAXDOP, CE version | Outside source control | Code you own and can change today |
| Automatic plan correction | Azure SQL baseline protection | Occasional unexpected forcing | When you need full manual control (document it) |
| Code / index fix | Root cause known | Release cycle | Mid-incident when minutes matter |
This is almost always parameter sniffing. SQL Server compiled the plan for the first parameter values it saw, maybe a tiny customer, and now reuses it for a customer with 2 million rows. SSMS looks fast because it runs with SET ARITHABORT ON (the app's SqlClient uses OFF), so it gets a separate cache entry and compiles a fresh plan for my values.
I confirm it in Query Store: the regressed query, two plan ids, and in the plan XML ParameterCompiledValue vs ParameterRuntimeValue. Mitigate by forcing the good plan. Then fix properly: OPTION (RECOMPILE) for infrequent queries, OPTIMIZE FOR, a Query Store hint, splitting code paths, or an index that makes one plan good for everyone. SQL Server 2022's PSP optimisation helps some cases.
First I confirm it's the release: Application Insights with the deployment annotation, comparing p95 by operation before and after. Then I check where the time goes: in the slow operation, are SQL dependencies longer (a worse query) or more numerous (N+1)? Next, Query Store on Azure SQL: Regressed Queries and Top Resource Consuming Queries show which statement got worse and whether its plan changed. I map that SQL back to code with TagWith comments (or the text), then read the LINQ diff: typical culprits are a non-sargable predicate, a new collection Include, a lost projection, or a parameter type change. I mitigate first: roll back or flag the change off; force the old plan only if it's purely a plan regression. Then fix the LINQ, verify the plan, and add query tags, a perf test and Query Store alerts. The trade-off: rollback is fastest, but only the root cause stops it recurring.
Forcing only works while the optimiser can still produce that plan. If an index it uses is dropped or renamed, the query text or SET options change (so it is a different query_id), or a schema change makes the plan invalid, forcing fails and SQL Server quietly compiles a normal plan. I notice through force_failure_count and last_force_failure_reason_desc in sys.query_store_plan, the query_store_plan_forcing_failed extended event, or a new plan_id appearing for the query. I also keep Query Store healthy (READ_WRITE, not full) and review forced plans after releases, because plans and data evolve.
How to tell it (STAR)
**S:** During a CPU incident on our [payments] database, I opened Query Store and found no data for the last three weeks. **T:** I needed to work out why so it wouldn't happen during the next incident. **A:** Query Store had flipped to read-only because its 100 MB limit was full of near-duplicate ad hoc queries from a batch job. I raised the limit, set capture mode to auto with size-based cleanup, put it back to read-write and got the batch job parameterised. Then I added an alert on Query Store state and moved its settings into our infrastructure code. **R:** We've had full history for every incident since, and the next regression was found and mitigated in [under 15 minutes].
Last updated 23 Nov 2026.