SQL Server Query Store Tutorial: Find Slow Queries, Compare Plans and Force a Plan

SQL Server 13 min readUpdated Nov 20, 2026
4 views0 comments

The server was slow last night, and this morning everything looks fine. Which query was it? The plan cache only remembers what is in memory right now. Query Store is the black box recorder of SQL Server: it saves every query, every plan it used and how long each run took, inside the database, so the history survives restarts. In this tutorial you switch it on, run a small workload, find the most expensive query, fix it, compare its two plans and force the good one.

Part of the SQL Server for Beginners series. This article is the written version of lesson 20 of the Bigland Network video course. Every script below was run in SQL Server Management Studio on a test instance (SQL Server 2025 Developer), and the results shown are the real ones. Times in milliseconds will differ on your machine; the reads and the counts will be the same. Run every example on a test server, not on production.


Contents

1. Why Query Store: the plan cache forgets

SQL Server already keeps statistics for the plans in its cache (sys.dm_exec_query_stats). That is useful, but the memory is short: a restart, memory pressure, a recompile or a new plan, and the history is gone. It also only shows the current plan of a query.

Plan cache (memory) Query Store (in the database)
Only the plans in memory now Queries, plans and runtime statistics
Lost after a restart Survives restarts, backups and restores (it is part of the database)
Lost when memory is short Kept for 30 days by default (stale query threshold)
Only the latest plan of a query Every plan a query has used, side by side
Read it with DMVs Views sys.query_store_* and built in SSMS reports

Query Store exists since SQL Server 2016 and is on by default for new databases from SQL Server 2022. Databases created on older versions, or upgraded ones, may still have it off.

For the general method of measuring a slow query (STATISTICS IO and TIME, reading the actual plan, sargable filters), see the related guide How to Find and Fix Slow Queries in SQL Server and lesson 13: Query Performance Tuning.

2. How Query Store records

  1. You run a query. The optimizer compiles a plan.
  2. Query Store saves the query text and the plan.
  3. Every time the query runs, it adds runtime statistics (executions, duration, CPU, logical reads, memory…) to the current time interval (60 minutes by default).
  4. The data is written asynchronously into the database (every 15 minutes by default, DATA_FLUSH_INTERVAL_SECONDS). The views also show what is still in memory, so you can query it at once.

Four catalog views tell the whole story. You join them in a chain:

View What it holds Join
sys.query_store_query_text The text of each statement query_text_id
sys.query_store_query One query_id per query (text + context settings) query_id
sys.query_store_plan One or more plans per query, is_forced_plan plan_id
sys.query_store_runtime_stats Runs, avg_duration (microseconds), avg_logical_io_reads… per plan and interval –

3. The test table

The lesson uses the series test database BiglandDemo plus a bigger table, dbo.Orders, so that a slow query really has work to do: 200,000 orders from 2,000 customers in US cities.

USE BiglandDemo;
CREATE TABLE dbo.Orders (
    OrderId    INT IDENTITY(1,1) CONSTRAINT PK_Orders PRIMARY KEY,
    CustomerId INT NOT NULL,
    City       VARCHAR(30) NOT NULL,
    Amount     DECIMAL(10,2) NOT NULL,
    OrderDate  DATE NOT NULL);
INSERT INTO dbo.Orders (CustomerId, City, Amount, OrderDate)
SELECT n % 2000 + 1,
       CHOOSE(n % 6 + 1, 'New York', 'Chicago', 'Houston', 'Seattle', 'Boston', 'Denver'),
       (n % 97) * 5 + 10,
       DATEADD(DAY, n % 365, '2026-01-01')
FROM (SELECT TOP (200000) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) - 1 AS n
      FROM sys.all_objects a CROSS JOIN sys.all_objects b) AS t;

SELECT COUNT(*) AS Orders,
       COUNT(DISTINCT CustomerId) AS Customers,
       MIN(OrderDate) AS FirstDay,
       MAX(OrderDate) AS LastDay
FROM dbo.Orders;
Orders Customers FirstDay LastDay
200000 2000 2026-01-01 2026-12-31

The only index is the primary key on OrderId. There is no index on CustomerId yet: that is the problem we will find.

4. Switch Query Store on

ALTER DATABASE BiglandDemo SET QUERY_STORE = ON
    (OPERATION_MODE = READ_WRITE, QUERY_CAPTURE_MODE = ALL);

ALTER DATABASE BiglandDemo SET QUERY_STORE CLEAR;  -- demo only: start empty

SELECT actual_state_desc, query_capture_mode_desc,
       max_storage_size_mb, current_storage_size_mb
FROM sys.database_query_store_options;
actual_state_desc query_capture_mode_desc max_storage_size_mb current_storage_size_mb
READ_WRITE ALL 1000 0

READ_WRITE means it records. QUERY_CAPTURE_MODE = ALL captures every query, even tiny ones, which is handy for a demo. CLEAR deletes everything Query Store has collected: use it only on a test database. In SSMS you can do the same from the database Properties > Query Store page.

5. The options you should know

Option Meaning
OPERATION_MODE READ_WRITE records, READ_ONLY keeps the data but adds nothing new.
QUERY_CAPTURE_MODE AUTO (default, best for production) skips small, rare queries; ALL captures everything; NONE captures no new queries; CUSTOM lets you set thresholds.
MAX_STORAGE_SIZE_MB The size limit (1000 MB by default from SQL Server 2019). When the store is full it switches to READ_ONLY and stops recording.
SIZE_BASED_CLEANUP_MODE AUTO removes the oldest, cheapest queries when the store gets close to full.
CLEANUP_POLICY (STALE_QUERY_THRESHOLD_DAYS) How many days of history to keep (30 by default).
INTERVAL_LENGTH_MINUTES The size of each statistics bucket (60 by default).
DATA_FLUSH_INTERVAL_SECONDS How often the in-memory data is written to disk (900 seconds by default).

A production-style setting:

ALTER DATABASE BiglandDemo SET QUERY_STORE = ON
    (OPERATION_MODE = READ_WRITE,
     QUERY_CAPTURE_MODE = AUTO,
     MAX_STORAGE_SIZE_MB = 1000,
     SIZE_BASED_CLEANUP_MODE = AUTO,
     CLEANUP_POLICY = (STALE_QUERY_THRESHOLD_DAYS = 30));

6. A busy day: the workload

We simulate a busy day with two loops. First the sales report for customer 42, twenty times:

DECLARE @i INT = 1, @total DECIMAL(12,2);
WHILE @i <= 20
BEGIN
    SELECT @total = SUM(Amount) FROM dbo.Orders WHERE CustomerId = 42;
    SET @i += 1;
END;
SELECT 42 AS CustomerId, @total AS TotalAmount, 20 AS Runs;
CustomerId TotalAmount Runs
42 24825.00 20

Then a small lookup by primary key, fifty times:

DECLARE @i INT = 1, @city VARCHAR(30);
WHILE @i <= 50
BEGIN
    SELECT @city = City FROM dbo.Orders WHERE OrderId = 4242;
    SET @i += 1;
END;
SELECT 4242 AS OrderId, @city AS City, 50 AS Runs;
OrderId City Runs
4242 Denver 50

7. Find the most expensive query

SELECT TOP 5 q.query_id,
       SUM(rs.count_executions) AS runs,
       CAST(AVG(rs.avg_duration) / 1000 AS DECIMAL(10,2)) AS avg_ms,
       CAST(AVG(rs.avg_logical_io_reads) AS INT) AS avg_reads,
       LEFT(qt.query_sql_text, 55) AS query_text
FROM sys.query_store_query AS q
JOIN sys.query_store_query_text AS qt ON qt.query_text_id = q.query_text_id
JOIN sys.query_store_plan AS p ON p.query_id = q.query_id
JOIN sys.query_store_runtime_stats AS rs ON rs.plan_id = p.plan_id
WHERE qt.query_sql_text LIKE '%dbo.Orders%'
  AND qt.query_sql_text NOT LIKE '%query_store%'
GROUP BY q.query_id, qt.query_sql_text
ORDER BY SUM(rs.avg_logical_io_reads * rs.count_executions) DESC;
query_id runs avg_ms avg_reads query_text
3 20 20.60 991 (@total decimal(12,2))SELECT @total = SUM(Amoun…
5 50 0.02 3 (@city varchar(30))SELECT @city = City FROM dbo….

How to read it:

  • Durations are stored in microseconds, so we divide by 1000 to get milliseconds.
  • Query 5 ran the most (50 times) but each run reads only 3 pages. Query 3 ran 20 times but reads 991 pages every time: 19,820 reads in total against 150. Sort by total work (runs times reads or runs times duration), not by one run or by the number of runs.
  • The text starts with the variable in brackets: Query Store saves the statement the way SQL Server compiled it.
  • Your query_id numbers can differ: they depend on what ran before in the database.

The filter NOT LIKE '%query_store%' hides our own detective queries. On a real server you would filter on the time window instead, using sys.query_store_runtime_stats_interval.

8. The built in reports in SSMS

You do not have to type the query every time. In Object Explorer expand Databases > BiglandDemo > Query Store. The reports are:

  • Regressed Queries: queries that got slower recently (usually a plan change).
  • Overall Resource Consumption: totals per time interval.
  • Top Resource Consuming Queries: the same list as above, as a chart. Start here.
  • Queries With Forced Plans: what you forced, and whether forcing failed.
  • Queries With High Variation: queries whose duration jumps around (often parameter sniffing).
  • Query Wait Statistics: what the queries waited for (CPU, locks, disk…).
  • Tracked Queries: follow one query_id over time.

Click a bar to see the plans of that query in the lower pane; the report also has a Force Plan button.

9. Fix the query and compare its plans

Query 3 is slow because there is no index on CustomerId: SQL Server scans the whole table (991 pages) to find the 100 orders of customer 42. The fix is an index on CustomerId that also carries Amount, so the index alone can answer the report (no lookup back to the table):

CREATE INDEX IX_Orders_CustomerId ON dbo.Orders (CustomerId) INCLUDE (Amount);

-- the same report, 20 more times
DECLARE @i INT = 1, @total DECIMAL(12,2);
WHILE @i <= 20
BEGIN
    SELECT @total = SUM(Amount) FROM dbo.Orders WHERE CustomerId = 42;
    SET @i += 1;
END;
SELECT 42 AS CustomerId, @total AS TotalAmount, 20 AS Runs;

Same answer: 24825.00 after 20 runs. Now compare the plans of the query:

SELECT p.query_id, p.plan_id,
       SUM(rs.count_executions) AS runs,
       CAST(AVG(rs.avg_duration) / 1000 AS DECIMAL(10,2)) AS avg_ms,
       CAST(AVG(rs.avg_logical_io_reads) AS INT) AS avg_reads,
       p.is_forced_plan
FROM sys.query_store_plan AS p
JOIN sys.query_store_runtime_stats AS rs ON rs.plan_id = p.plan_id
JOIN sys.query_store_query AS q ON q.query_id = p.query_id
JOIN sys.query_store_query_text AS qt ON qt.query_text_id = q.query_text_id
WHERE qt.query_sql_text LIKE '%SUM(Amount)%'
  AND qt.query_sql_text NOT LIKE '%query_store%'
GROUP BY p.query_id, p.plan_id, p.is_forced_plan
ORDER BY p.plan_id;
query_id plan_id runs avg_ms avg_reads is_forced_plan
3 3 20 20.60 991 0
3 8 20 0.07 3 0

One query, two plans: plan 3 (table scan) and plan 8 (index seek). 991 reads against 3 is about 330 times less work on every run. The plan cache would only show plan 8 now; Query Store kept both, with their numbers, which is your before-and-after proof.

10. Plan regression and forcing a plan

A plan regression is the opposite story: a query is fast on Monday with plan A; on Tuesday, after a statistics update or a restart, the optimizer chooses plan B and the query becomes slow. Query Store shows both plans and lets you tell SQL Server to use the good one again:

EXEC sp_query_store_force_plan @query_id = 3, @plan_id = 8;

SELECT query_id, plan_id, is_forced_plan
FROM sys.query_store_plan
WHERE query_id = 3;
query_id plan_id is_forced_plan
3 3 0
3 8 1

Forcing does not change your data or your code; it only tells the optimizer which plan to use for that query, and it survives restarts. If the forced plan becomes impossible (for example its index is dropped), forcing fails and SQL Server compiles a new plan: check force_failure_count and last_force_failure_reason_desc in sys.query_store_plan. From SQL Server 2017, automatic plan correction (ALTER DATABASE CURRENT SET AUTOMATIC_TUNING (FORCE_LAST_GOOD_PLAN = ON)) can force the last good plan for you when it detects a regression.

11. A classic error

-- a typo in the ids
EXEC sp_query_store_force_plan @query_id = 999, @plan_id = 999;

Msg 12402, Level 11: Query with provided query_id (999) is not found in the Query Store for database (6). Check the query_id value and rerun the command.

The ids are per database and change when the store is cleared. Copy them from the views or the report, in the right database.

12. Common mistakes and best practices

Common mistakes

  • Assuming Query Store is on: before SQL Server 2022 it was off by default. Check sys.database_query_store_options.
  • Leaving QUERY_CAPTURE_MODE = ALL in production: the store fills up with tiny, one-off queries.
  • A store that is too small: it turns READ_ONLY and silently stops recording. actual_state_desc differs from desired_state_desc and readonly_reason tells you why.
  • Forcing a plan and forgetting it: data grows, and the forced plan can become the slow one.
  • Judging a query by one run, or by the number of runs, instead of the total work.
  • Comparing queries across databases: Query Store is per database.

Best practices

  • Keep Query Store on in every user database (READ_WRITE, capture mode AUTO).
  • Check its state and size from time to time; leave SIZE_BASED_CLEANUP_MODE = AUTO.
  • Start an investigation with Top Resource Consuming Queries and Regressed Queries.
  • Fix the cause first (an index, a sargable filter, updated statistics, a better query). Force a plan only as a quick, safe fix, and review forced plans regularly.
  • Keep your before-and-after numbers: Query Store gives them to you for free.

13. Practice with answers, and clean up

  1. Is Query Store on in BiglandDemo, and how much space does it use?
  2. Which query on the Orders table ran the most times?
  3. Which plans are forced right now?
-- 1
SELECT actual_state_desc,
       current_storage_size_mb,
       max_storage_size_mb
FROM sys.database_query_store_options;
actual_state_desc current_storage_size_mb max_storage_size_mb
READ_WRITE 1 1000
-- 2
SELECT TOP 1 q.query_id,
       SUM(rs.count_executions) AS runs,
       LEFT(qt.query_sql_text, 55) AS query_text
FROM sys.query_store_query AS q
JOIN sys.query_store_query_text AS qt ON qt.query_text_id = q.query_text_id
JOIN sys.query_store_plan AS p ON p.query_id = q.query_id
JOIN sys.query_store_runtime_stats AS rs ON rs.plan_id = p.plan_id
WHERE qt.query_sql_text LIKE '%dbo.Orders%'
  AND qt.query_sql_text NOT LIKE '%query_store%'
GROUP BY q.query_id, qt.query_sql_text
ORDER BY runs DESC;
query_id runs query_text
5 50 (@city varchar(30))SELECT @city = City FROM dbo….
-- 3
SELECT query_id, plan_id
FROM sys.query_store_plan
WHERE is_forced_plan = 1;
query_id plan_id
3 8

Clean up: unforce the plan first, then drop the index it needs.

EXEC sp_query_store_unforce_plan @query_id = 3, @plan_id = 8;
DROP INDEX IX_Orders_CustomerId ON dbo.Orders;

SELECT COUNT(*) AS forced_plans
FROM sys.query_store_plan
WHERE is_forced_plan = 1;

Result: 0 forced plans.

Frequently asked questions

Does Query Store slow down my server?

The overhead is small for normal workloads, especially with capture mode AUTO. Very busy systems with thousands of different ad hoc queries should watch its size and use AUTO or CUSTOM capture.

Is Query Store data in my backups?

Yes. It lives in the database, so a backup and restore brings the history with it, which is useful to analyse a production problem on a test server.

Why do I not see my query?

With capture mode AUTO, very small or rare queries are skipped. The store may also be READ_ONLY because it is full: check actual_state_desc.

What to learn next

The next lesson covers locking and blocking: why one query waits for another, and how to find who is blocking whom. Previous lesson: Lesson 19: Full Text Search.

The whole series

Sources and further reading

  • Microsoft Learn, Transact-SQL reference (Database Engine), on learn.microsoft.com: the official syntax for the statements used here.
  • Microsoft Learn, Query Store, sys.query_store_* views and sp_query_store_force_plan, for the full details of each feature.
Did you find this helpful?Tap the heart to let us know. It takes one second and no account.

More tutorials like this

Leave a Comment

Your email address will not be published. Required fields are marked *

Bigland Network IT

Practical tutorials for people who run, build and fix things: operating systems, databases, development, networking and security.

Topics

More

Site

© 2026 Bigland Network. All rights reserved.Always test commands on a non-production system first.
Scroll to Top