Summary
What pg_stat_statements is in PostgreSQL, what Performance Schema is in MySQL, Query Store + DMV is in SQL Server. When the system slows down, adding an index by guess or changing a parameter is forbidden. First we measure. In this guide you will learn how to enable Query Store, how to find the 20 most expensive queries by total time, how to diagnose the top 3 queries precisely, how to detect plan regression, and how to decide the fix. This article is the first cluster that starts the SQL Server leg of the Performance Pillar.
Scenario
Time is 11:42. The application team writes: Pages open in 8 seconds, yesterday it was 400 ms. CPU is at 90%, disk I/O is maxed out. The team says let's scale up the server. The DBA says stop, let's measure first. Because a deploy happened last night. Maybe a new query was added. Maybe an index was deleted. Maybe a plan changed. In SQL Server, plan changes are more insidious than in PostgreSQL and MySQL. Because the same query can run with a good plan yesterday and a bad plan today. This is called plan regression. Scaling up by guess hides the problem. First we need to find which query is eating the system and whether its plan changed.
Concept: What Is Query Store?
Query Store is SQL Server's internal measurement and plan history system. Which query ran how many times, how long it took in total, how much CPU it used, how much I/O it did, with which plan it ran — it records all of them.
The difference from pg_stat_statements in PostgreSQL is this: Query Store does not only keep statistics, it also keeps plan history. So you can compare which plan a query ran with yesterday and which plan it runs with today. This is the most powerful tool for detecting plan regression.
The 3 most important sources:
- •Query Store: Persistent measurement and plan history. Survives restart.
- •DMV (Dynamic Management Views): Real-time measurement. Views like
sys.dm_exec_query_stats,sys.dm_exec_requests,sys.dm_os_wait_stats. - •SSMS Dashboard: Graphical interface of Query Store. Ideal for a quick look.
Step 0: Is Query Store On?
First check if it is on.
SELECT name, is_query_store_on, query_store_options
FROM sys.databases
WHERE name = 'ProductionDB';is_query_store_on must be 1. If it is off, turn it on:
ALTER DATABASE ProductionDB
SET QUERY_STORE = ON;Configure Query Store settings for production:
ALTER DATABASE ProductionDB
SET QUERY_STORE (
OPERATION_MODE = READ_WRITE,
CLEANUP_POLICY = (STALE_QUERY_THRESHOLD_DAYS = 30),
DATA_FLUSH_INTERVAL_SECONDS = 900,
INTERVAL_LENGTH_MINUTES = 60,
MAX_STORAGE_SIZE_MB = 1024,
QUERY_CAPTURE_MODE = AUTO,
SIZE_BASED_CLEANUP_MODE = AUTO
);▸How to Interpret the Settings?
- •
STALE_QUERY_THRESHOLD_DAYS = 30: Query history older than 30 days is deleted. Keeping longer bloats disk. - •
MAX_STORAGE_SIZE_MB = 1024: Query Store uses at most 1 GB. If full, it deletes old data. Do not keep smaller. - •
QUERY_CAPTURE_MODE = AUTO: Records important queries, not all queries.ALLmode bloats Query Store with small queries. - •
INTERVAL_LENGTH_MINUTES = 60: Measurement interval is 60 minutes. Smaller interval means more detail but bigger data.
If the system is slow while Query Store is off, first turn on Query Store, wait 1 hour, then diagnose. Without history, diagnosis cannot be done.
Step 1: Find the 20 Most Expensive Queries
This is the main query. It sorts by total time.
SELECT TOP 20
LEFT(qst.query_sql_text, 150) AS query_text,
qrs.count_executions AS exec_count,
CAST(qrs.avg_duration / 1000.0 AS DECIMAL(10,2)) AS avg_time_ms,
CAST(qrs.max_duration / 1000.0 AS DECIMAL(10,2)) AS max_time_ms,
CAST(qrs.avg_cpu_time / 1000.0 AS DECIMAL(10,2)) AS avg_cpu_ms,
CAST(qrs.avg_logical_io_reads AS INT) AS avg_logical_reads,
CAST(qrs.avg_rowcount AS INT) AS avg_rowcount,
qrs.last_execution_time
FROM sys.query_store_query qsq
JOIN sys.query_store_query_text qst
ON qsq.query_text_id = qst.query_text_id
JOIN sys.query_store_plan qsp
ON qsp.query_id = qsq.query_id
JOIN sys.query_store_runtime_stats qrs
ON qrs.plan_id = qsp.plan_id
WHERE qrs.last_execution_time > DATEADD(HOUR, -24, GETUTCDATE())
ORDER BY qrs.avg_duration * qrs.count_executions DESC;Easier way, use DMVs:
SELECT TOP 20
LEFT(st.text, 150) AS query_text,
qs.execution_count AS exec_count,
qs.total_elapsed_time / 1000.0 / qs.execution_count AS avg_time_ms,
qs.total_worker_time / 1000.0 / qs.execution_count AS avg_cpu_ms,
qs.total_logical_reads / qs.execution_count AS avg_logical_reads,
qs.total_rows / qs.execution_count AS avg_rowcount,
qs.last_execution_time
FROM sys.dm_exec_query_stats qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) st
WHERE qs.last_execution_time > DATEADD(HOUR, -24, GETUTCDATE())
ORDER BY qs.total_elapsed_time DESC;▸How to Read the Output?
- •
total_time: This is the query that tires the system the most. Look at this first. - •
avg_time: If a single query is fast but runs many times, it may be N+1. - •
avg_logical_reads / avg_rowcount: If the ratio is over 100, the query reads unnecessary rows. The index may be missing. - •
avg_cpu: If CPU is high but logical reads are low, the query may do CPU-intensive work. Functions, sorting, hash.
▸Quick Look with SSMS
In SSMS, right-click the database, choose Top Resource Consuming Queries from the Query Store menu. You see the most expensive queries in a chart. If you click a query, you see its plan history. This is ideal for quick diagnosis without writing DMV queries.
Step 2: Diagnose the Top 3 Queries Precisely
You found the 20 most expensive queries. Now focus on the top 3.
For each query, answer 3 questions:
▸Question 1: Is the Query Really Slow, or Does It Run Too Often?
- •Slow query: Average time is high, execution count is low. Solution: Index, plan, query design.
- •Frequent query: Average time is low, execution count is very high. Solution: N+1 fix, cache, batch.
We made the same distinction in PostgreSQL and MySQL articles. In SQL Server the rule is the same.
▸Question 2: Is the Plan Bad? Is There Plan Regression?
This is the most important SQL Server-specific question.
-- List plan history of a query
SELECT
qsp.plan_id,
qsp.is_forced_plan,
qsp.last_execution_time,
qrs.avg_duration / 1000.0 AS avg_time_ms,
qrs.count_executions AS exec_count
FROM sys.query_store_plan qsp
JOIN sys.query_store_runtime_stats qrs ON qrs.plan_id = qsp.plan_id
WHERE qsp.query_id = 123
ORDER BY qrs.last_execution_time DESC;If the same query ran with an average of 100 ms yesterday and 5000 ms today, there is plan regression. The query did not change, the plan changed. Reasons:
- •Statistics were updated.
- •An index was added or deleted.
- •Data distribution changed.
- •Parameter sniffing problem occurred.
To see the plan:
SET STATISTICS PROFILE ON;
SELECT * FROM Orders WHERE CustomerID = 123 AND Status = 'Open';
SET STATISTICS PROFILE OFF;Or in SSMS run the query with Include Actual Execution Plan turned on. You see the real plan.
When looking at the plan, watch for:
- •Clustered Index Scan: Scans the whole table. Disaster on a large table.
- •Index Seek: Search with index. Usually good.
- •Key Lookup: Return to the table for columns not found in the index. Many Key Lookups are fixed with a covering index.
- •Hash Match: Hash Join or Hash Aggregate. Normal for large data but can pressure memory.
- •Sort: Uses memory for sorting. Can be fixed with an index.
- •Warning: If there is an exclamation mark on the plan, there is a missing statistics or missing index warning.
▸Question 3: Does the Query Use an Index?
Find missing index suggestions via Query Store:
SELECT
LEFT(qst.query_sql_text, 150) AS query_text,
qrs.avg_duration / 1000.0 AS avg_time_ms,
qrs.count_executions AS exec_count
FROM sys.query_store_query qsq
JOIN sys.query_store_query_text qst ON qst.query_text_id = qsq.query_text_id
JOIN sys.query_store_plan qsp ON qsp.query_id = qsq.query_id
JOIN sys.query_store_runtime_stats qrs ON qrs.plan_id = qsp.plan_id
WHERE qsp.query_id IN (
SELECT query_id FROM sys.query_store_plan
WHERE plan_id IN (
SELECT plan_id FROM sys.dm_db_missing_index_details
)
)
ORDER BY qrs.avg_duration DESC;More practical way, look at missing index DMVs:
SELECT TOP 20
migs.avg_total_user_cost * migs.avg_user_impact * (migs.user_seeks + migs.user_scans) AS improvement_score,
mid.statement AS table_name,
mid.equality_columns,
mid.inequality_columns,
mid.included_columns
FROM sys.dm_db_missing_index_groups mig
JOIN sys.dm_db_missing_index_group_stats migs ON migs.group_handle = mig.index_group_handle
JOIN sys.dm_db_missing_index_details mid ON mid.index_handle = mig.index_handle
WHERE mid.database_id = DB_ID('ProductionDB')
ORDER BY improvement_score DESC;If improvement_score is high, that index is really useful. But do not add immediately. First test in a test environment.
Find unused indexes too:
SELECT
OBJECT_NAME(i.object_id) AS table_name,
i.name AS index_name,
ius.user_seeks + ius.user_scans AS read_count,
ius.user_updates AS write_count
FROM sys.indexes i
LEFT JOIN sys.dm_db_index_usage_stats ius
ON ius.object_id = i.object_id AND ius.index_id = i.index_id
WHERE ius.user_seeks IS NULL AND i.type_desc <> 'HEAP'
AND OBJECT_NAME(i.object_id) NOT LIKE 'sys%'
ORDER BY ius.user_updates DESC;If read count is 0 but write count is high, that index only slows writes.
Step 3: Look at Currently Running Queries
Past summary is not enough. Look at what is running now.
SELECT
r.session_id,
r.status,
r.wait_type,
r.wait_time / 1000.0 AS wait_sec,
r.cpu_time / 1000.0 AS cpu_sec,
r.logical_reads,
LEFT(st.text, 150) AS query_text
FROM sys.dm_exec_requests r
CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) st
WHERE r.session_id > 50
ORDER BY r.cpu_time DESC;If a query has been running for 5 minutes, it may be locking the system right now. The past summary will show it in 5 minutes. But you must see it now.
Look at the most common wait types:
SELECT TOP 20
wait_type,
waiting_tasks_count AS waiting_tasks,
wait_time_ms / 1000.0 AS total_wait_sec,
max_wait_time_ms / 1000.0 AS max_wait_sec
FROM sys.dm_os_wait_stats
WHERE wait_type NOT IN (
'BROKER_EVENTHANDLER', 'BROKER_RECEIVE_WAITFOR', 'BROKER_TASK_STOP',
'CHECKPOINT_QUEUE', 'CLR_AUTO_EVENT', 'CLR_MANUAL_EVENT',
'DISPATCHER_QUEUE_SEMAPHORE', 'FT_IFTS_SCHEDULER_IDLE_WAIT',
'HADR_FILESTREAM_IOMGR_IOCOMPLETION', 'LAZYWRITER_SLEEP',
'LOGMGR_QUEUE', 'ONDEMAND_TASK_QUEUE', 'REQUEST_FOR_DEADLOCK_SEARCH',
'RESOURCE_QUEUE', 'SERVER_IDLE_CHECK', 'SLEEP_TASK',
'SLEEP_SYSTEMTASK', 'SQLTRACE_BUFFER_FLUSH', 'SQLTRACE_INCREMENTAL_FLUSH_SLEEP',
'SQLTRACE_WAIT_ENTRIES', 'WAITFOR', 'XE_DISPATCHER_WAIT', 'XE_TIMER_EVENT'
)
ORDER BY wait_time_ms DESC;Interpret wait types:
- •
PAGEIOLATCH_SH: Waiting for data from disk. Buffer Pool may be small or index missing. - •
LCK_M_X: Waiting for a lock. Will be covered in detail in the next lock cluster. - •
CXPACKET: Parallel query waiting. Related to parallelism settings. - •
SOS_SCHEDULER_YIELD: CPU waiting. CPU pressure exists. - •
MEMORY_GRANT_QUEUE: Waiting for memory grant. Related to Memory Grant settings.
Step 4: Decide the Fix
Diagnosis is complete. Now decide. Choose 1 action per query.
▸Decision 1: Add an Index
If the plan does Clustered Index Scan and there is a missing index suggestion, add an index.
-- First test in a test environment
CREATE INDEX IX_Orders_Customer_Status
ON Orders (CustomerID, Status)
INCLUDE (Total, CreatedAt);
-- Then get the plan again
SELECT * FROM Orders WHERE CustomerID = 123 AND Status = 'Open';Creating an index on a large table can lock the table. Use ONLINE = ON:
CREATE INDEX IX_Orders_Customer_Status
ON Orders (CustomerID, Status)
INCLUDE (Total, CreatedAt)
WITH (ONLINE = ON);▸Decision 2: Fix the Query
If the query does SELECT * and only 3 columns are needed, fix the query.
-- Bad:
SELECT * FROM Orders WHERE CustomerID = 123;
-- Good:
SELECT OrderID, Total, CreatedAt FROM Orders WHERE CustomerID = 123;If the query uses a function-wrapped WHERE, fix it.
-- Bad: Index is not used
SELECT * FROM Orders WHERE CAST(CreatedAt AS DATE) = '2026-11-30';
-- Good: Index is used
SELECT * FROM Orders WHERE CreatedAt >= '2026-11-30' AND CreatedAt < '2026-12-01';▸Decision 3: Force the Plan — Plan Forcing
If there is plan regression and the old plan is better, force the old plan.
-- Force the plan via Query Store
EXEC sp_query_store_force_plan @query_id = 123, @plan_id = 456;Plan forcing is a temporary solution. It is not a permanent solution without fixing the root cause. Update statistics, fix the index, then remove plan forcing.
-- Remove plan forcing
EXEC sp_query_store_unforce_plan @query_id = 123, @plan_id = 456;▸Decision 4: Fix N+1
If the query averages 8 ms but runs 2 million times a day, there is N+1. Do not run queries in a loop. Fetch with a single JOIN.
▸Decision 5: Change Parameters — Last Resort
If the query is correct, the index is correct, the plan is correct, but the system is still slow, then look at parameters. Memory and parallelism settings will be covered in detail in the next cluster article.
Verification: Did the Fix Work?
Record the baseline measurement before the fix. Measure the same query again after the fix.
SELECT
qrs.avg_duration / 1000.0 AS avg_time_ms,
qrs.count_executions AS exec_count,
qrs.avg_cpu_time / 1000.0 AS avg_cpu_ms
FROM sys.query_store_runtime_stats qrs
JOIN sys.query_store_plan qsp ON qsp.plan_id = qrs.plan_id
WHERE qsp.query_id = 123
ORDER BY qrs.last_execution_time DESC;Success criteria:
- •Did total time drop?
- •Did average time drop?
- •Did logical reads drop?
- •Did plan regression resolve?
If you cannot say yes to these questions, the fix did not work. Revert it, diagnose again.
7 Common Mistakes
First mistake: Adding an index by guess without enabling Query Store. Do not change without measuring.
Second mistake: Choosing the most expensive query by average time. What tires the system is total time.
Third mistake: Not noticing plan regression. Thinking the plan did not change because the query did not change is the sneakiest mistake.
Fourth mistake: Moving unnecessary columns with SELECT *. It increases Key Lookup count.
Fifth mistake: Not deleting unused indexes. Every unused index slows every write.
Sixth mistake: Thinking plan forcing is a permanent solution. Plan forcing is a temporary bandage. Fix the root cause.
Seventh mistake: Trying to fix a bad query by changing parameters. First fix the query, then look at parameters.
Checklist
- Query Store is on checked
- Query Store settings configured for production
- 20 most expensive queries listed by total time
- Top 3 queries diagnosed precisely
- Slow query vs frequent query distinction made
- Plan regression existence checked
- Real plan obtained
- Missing index suggestions checked
- Currently running queries checked
- Wait types checked
- 1 fix action chosen
- Index tested in test environment first
ONLINE = ONused on large tables- Total and average time measured again after fix
- Useless fix reverted
Conclusion
In SQL Server, as in other engines, performance problems start with measurement. Query Store is the mirror of the system. First look in the mirror, then fix. But in SQL Server there is one more step: Look at plan history. Because even if the query stays the same, the plan can change. Without catching plan regression, you cannot manage SQL Server performance.
Next cluster: SQL Server Memory Tuning — Buffer Pool and Memory Grant. Because after finding the most expensive query, next is to set memory correctly.
Related Articles
- •Pillar: Performance Guide — Performance & Query Optimization
- •Cluster: [PostgreSQL] Finding the 20 Most Expensive Queries with pg_stat_statements
- •Cluster: [MySQL] Finding the 20 Most Expensive Queries with Performance Schema
- •Cluster: [Universal] EXPLAIN ANALYZE Reading Guide
- •Next: [SQL Server] Memory Tuning — Buffer Pool and Memory Grant