Finding the Queries That Use the Most CPU, and What Each Source Misses
The CPU alert fires on SQLPROD01. You run the usual query against sys.dm_exec_query_stats, sort by total_worker_time, and the top row says 1.4 seconds of CPU. The server has been busy for an hour, so that can’t be the whole answer.

To see how far off that can be, I built a small workload that used 56 to 62 seconds of CPU, and asked the plan cache, the procedure statistics and Query Store which query used the most. They each found different queries, gave different totals for the same query, and some parts of the workload didn’t appear in some of them at all.
The Test
I used two instances on one workstation with 14 logical processors: SQL Server 2019 (15.0.4500.2, Developer) and SQL Server 2025 (17.0.5015.4, Enterprise Developer). Each got a scratch database with a 200,000-row table of integers. I turned Query Store on in that database only, with QUERY_CAPTURE_MODE = ALL and a one-minute statistics interval. I didn’t change any instance setting. Each load ran for under two minutes, on one instance at a time.
The workload had four parts, all of which ran serially:
- A procedure,
cpu_loop, that runs aWHILEloop two million times doing integer arithmetic on variables, called 8 times. - 600 ad hoc
SELECTstatements against the table, identical except for one literal, so each one compiles its own plan. - A cross-join count with
OPTION (RECOMPILE), sent 10 times as an ad hoc batch. - The same statement inside a procedure,
recompile_proc, called 10 times.
The loop procedure looks like this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
CREATE OR ALTER PROCEDURE [dbo].[cpu_loop] ( @iterations int ) AS BEGIN SET NOCOUNT ON; DECLARE @i int = 0; DECLARE @x bigint = 0; WHILE @i < @iterations BEGIN SET @x = (@x + (@i * 7)) % 1000003; SET @i += 1; END; SELECT @x AS [x]; END; |
The Plan Cache: sys.dm_exec_query_stats
sys.dm_exec_query_stats has one row per statement in a cached plan. total_worker_time is the CPU used since that plan was compiled, in microseconds. When the plan leaves the cache, the row goes with it. The view also only includes finished executions.[1] Like the counters in Performance Counters Over Time, it’s a running total, so you need two samples to get a rate.
The table shows what each source reported for each part of the workload on SQL Server 2025, in milliseconds of CPU.
| Workload part | query_stats, largest row | query_stats, by query_hash | procedure_stats | Query Store |
|---|---|---|---|---|
cpu_loop x 8 |
no row | no row | 12,648 | no row |
| 600 ad hoc literals | 47 | 21,641 | n/a | 21,641 over 600 query_ids |
Ad hoc RECOMPILE x 10 |
no row | no row | n/a | 13,127 |
recompile_proc x 10 |
1,362 | 1,362 | 14,127 | 14,126 |
SQL Server 2019 followed the same pattern. Its cpu_loop used 7,384 ms, the 600 ad hoc statements 19,964 ms, and the two RECOMPILE cases 14,217 ms and 14,204 ms.
Row by row, the plan cache put the recompile_proc statement first at 1,362 ms. That row had execution_count = 1 and plan_generation_num = 11, so it described the last of the 10 executions. sys.dm_exec_procedure_stats reported 14,127 ms for the same procedure.
The ad hoc RECOMPILE batch had no row at all. The RECOMPILE hint tells the engine to discard the plan after the query runs.[2]
The 600 ad hoc statements used the most CPU in the plan cache, but no single row showed it. Each one had its own plan, and the biggest used 47 ms. query_hash is the same for queries that differ only by literal values,[1] so grouping by it puts them back together:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
USE [master]; SELECT TOP (10) [qs].[query_hash] , COUNT_BIG(1) AS [cached_entries] , SUM([qs].[execution_count]) AS [executions] , SUM([qs].[total_worker_time]) / 1000 AS [total_cpu_ms] , MIN(SUBSTRING([st].[text], ([qs].[statement_start_offset] / 2) + 1, 200)) AS [sample_statement] FROM [sys].[dm_exec_query_stats] AS [qs] CROSS APPLY [sys].[dm_exec_sql_text]([qs].[sql_handle]) AS [st] GROUP BY [qs].[query_hash] ORDER BY SUM([qs].[total_worker_time]) DESC; |
Grouped that way, the 600 rows became one row with 21,641 ms, the largest total in the plan cache.
The cpu_loop procedure had no rows in sys.dm_exec_query_stats on either version, even though its plan was cached. Its statements assign variables, loop, and return one variable, and none of them read a table. I didn’t find a documented reason for the missing rows. Its CPU (12.6 seconds on 2025, 7.4 on 2019) appeared only in sys.dm_exec_procedure_stats, which has one row per cached procedure plan.[3]
While checking this, I filtered sys.dm_exec_sql_text on objectid alone. An object id is only unique within a database, and the filter matched an unrelated procedure in another database with 3.7 million executions. Filter on dbid as well.
As a stand-in for eviction, I cleared the plan cache for the scratch database with ALTER DATABASE SCOPED CONFIGURATION CLEAR PROCEDURE_CACHE.[4] sys.dm_exec_query_stats went from 604 rows to 0 on SQL Server 2025 (the 600 ad hoc plans, the procedure’s statement and three internal statements), and sys.dm_exec_procedure_stats from 2 rows to 0. Query Store still had all 602 queries and the same 48,893 ms of CPU.
Query Store
sys.query_store_runtime_stats stores avg_cpu_time (in microseconds) and count_executions per plan per interval.[5] Multiply them and add up the intervals you care about:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
USE [SalesDb]; SELECT TOP (10) [q].[query_hash] , COUNT_BIG(DISTINCT [q].[query_id]) AS [query_ids] , SUM([rs].[count_executions]) AS [executions] , SUM([rs].[avg_cpu_time] * [rs].[count_executions]) / 1000 AS [total_cpu_ms] FROM [sys].[query_store_query] AS [q] INNER JOIN [sys].[query_store_plan] AS [p] ON [p].[query_id] = [q].[query_id] INNER JOIN [sys].[query_store_runtime_stats] AS [rs] ON [rs].[plan_id] = [p].[plan_id] INNER JOIN [sys].[query_store_runtime_stats_interval] AS [rsi] ON [rsi].[runtime_stats_interval_id] = [rs].[runtime_stats_interval_id] WHERE [rsi].[start_time] >= DATEADD(hour, -2, SYSUTCDATETIME()) GROUP BY [q].[query_hash] ORDER BY SUM([rs].[avg_cpu_time] * [rs].[count_executions]) DESC; |
Query Store recorded both RECOMPILE cases with all 10 executions each. The ad hoc batch and the procedure got separate query_id values but the same query_hash, so this query put them first at 27,252 ms on SQL Server 2025 and 28,420 ms on SQL Server 2019. That’s the largest consumer in the workload, and the plan cache showed 1,362 ms of it.
Query Store also had gaps:
cpu_loophad no Query Store rows either, with capture modeALL, on both versions. The documentation says queries inside stored procedures are always captured,[6] and I didn’t find anything that explains the gap. My guess is that statements that read no table produce no plan to record, but I haven’t confirmed it.- It only covers databases where it’s turned on. It’s on by default for new databases from SQL Server 2022, and off by default in 2016, 2017 and 2019.[7] Check
sys.database_query_store_optionsin each database rather than assuming. - The capture mode matters.
AUTO, the default from SQL Server 2019, captures queries based on execution count and resource use.[6] I switched the scratch database toAUTO, cleared Query Store, and ran the 600 ad hoc statements again. Query Store captured none of them on either version. The plan cache had all 600, with 21,696 ms on 2025 and 19,277 ms on 2019.
Query Store writes its data to disk in the database, asynchronously, on the DATA_FLUSH_INTERVAL_SECONDS schedule.[6] So it should survive a restart, apart from anything not yet flushed. I didn’t restart either instance to test that. If the top consumer turns out to be one query whose plan changed, Investigating Plan Regressions with Query Store covers comparing and forcing plans.
Queries Still Running: sys.dm_exec_requests
I ran a single-threaded cross-join that takes about 30 seconds, and queried each source at 10 and 20 seconds. cpu_time in sys.dm_exec_requests is in milliseconds.[8]
| Instance | At 20 s: requests cpu_time | At 20 s: query_stats | At 20 s: Query Store | After it finished |
|---|---|---|---|---|
| SQL Server 2019 | 20,176 ms | no row | query, no runtime row | 32,105 ms in both |
| SQL Server 2025 | 20,011 ms | no row | only the earlier run | 31,925 ms in both |
On SQL Server 2025 I’d run the same statement once before, so Query Store showed that earlier execution at 20 seconds, not the one in progress. Afterward it held both runs, 61,156 ms in total. Of the sources I checked, only sys.dm_exec_requests showed the CPU of a query while it ran.
Then I tested client timeouts. I ran another 30-second query three times with a 10-second client command timeout. sys.dm_exec_query_stats had no row for it on either version. Query Store had three executions with execution_type_desc = Aborted and about 30,010 ms of CPU across the three, which matches its documented execution types.[5] So an application that times out and retries can use CPU that the plan cache never shows.
A parallel query reports more CPU than elapsed time. At 30 seconds, a DOP 4 query on SQL Server 2025 showed cpu_time of 120,412 ms against total_elapsed_time of 30,118 ms. That’s four workers, each using close to 30 seconds.
Instance History: the Scheduler Monitor Ring Buffer
None of the views above say whether SQL Server is the process using the CPU. The RING_BUFFER_SCHEDULER_MONITOR records in sys.dm_os_ring_buffers do, with SQL Server’s CPU percentage and the system idle percentage. Microsoft documents the view, but says the record contents aren’t supported unless Microsoft’s documentation describes them or Microsoft directs you to use them. I didn’t find this record type described.[9] On both instances I saw one record a minute, with 256 records covering 255 minutes.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
USE [master]; DECLARE @ms_ticks bigint = ( SELECT [ms_ticks] FROM [sys].[dm_os_sys_info] ); SELECT DATEADD(millisecond, -1 * CONVERT(int, @ms_ticks - [rb].[timestamp]), GETDATE()) AS [event_time] , [rb].[record_xml].value(N'(./Record/SchedulerMonitorEvent/SystemHealth/ProcessUtilization)[1]', N'int') AS [sql_cpu_pct] , [rb].[record_xml].value(N'(./Record/SchedulerMonitorEvent/SystemHealth/SystemIdle)[1]', N'int') AS [idle_pct] FROM ( SELECT [r].[timestamp] , CONVERT(xml, [r].[record]) AS [record_xml] FROM [sys].[dm_os_ring_buffers] AS [r] WHERE [r].[ring_buffer_type] = N'RING_BUFFER_SCHEDULER_MONITOR' AND [r].[record] LIKE N'%<SystemHealth>%' ) AS [rb] ORDER BY [rb].[timestamp] DESC; |
Anything that isn’t SQL Server and isn’t idle is another process: 100 minus the two columns. Run it with QUOTED_IDENTIFIER on. sqlcmd leaves it off unless you pass -I, and the error, Msg 1934, mentions XML data type methods. On SQL Server 2025 the view also has a create_time column,[9] which saves the ms_ticks arithmetic.
I ran an 81-second DOP 4 query on SQL Server 2025. Four of 14 processors is about 29%. The query spanned two ring buffer records, and it ran for about 49 seconds of the second one. For that minute, the 2025 ring buffer showed 22% for SQL Server and 17% for other processes. The 2019 instance on the same workstation showed 1% for itself and 44% for other processes, against 11% to 26% in the minutes before the parallel test. Each instance counts only itself as SQL Server, so on a shared host another instance’s work shows up as “other”.
What Each Source Missed
| Source | Missed in this test |
|---|---|
sys.dm_exec_query_stats |
OPTION (RECOMPILE) batches, all but the last execution of a recompiled statement in a procedure, the WHILE loop, running queries, timed-out queries, anything evicted |
sys.dm_exec_procedure_stats |
Ad hoc work, anything evicted |
| Query Store | Databases where it’s off, the WHILE loop, running queries, and the 600 ad hoc statements under AUTO capture |
sys.dm_exec_requests |
Anything that already finished |
| Ring buffer | Which query, which database |
In this test, no single source saw all of the CPU. Query Store grouped by query_hash named the top query, but it missed the loop procedure and, under AUTO, the ad hoc statements. I’d start there where Query Store is on, check the plan cache grouped the same way, then sys.dm_exec_procedure_stats for procedures, and sys.dm_exec_requests for what’s running now. For the incident workflow around this, see Incident Response: Root Cause Analysis with an AI Partner.
Some limits:
- I tested one build of each version, on one workstation, with a synthetic workload. In the minutes before the parallel test, the ring buffers showed 11% to 26% of the CPU used outside SQL Server.
- I didn’t restart either instance, and I didn’t test eviction under real memory pressure.
CLEAR PROCEDURE_CACHEfor one database stood in for eviction. - I didn’t test
CUSTOMcapture mode, which lets you set the thresholds. - I tested
WHILEloops over variables only. I’d expect a loop whose statements read tables to have rows in both the plan cache and Query Store, but I didn’t test that.
Related: THREADPOOL Waits: Reproducing Worker Thread Exhaustion in SQL Server and Spinlock Contention for DBAs: Measure a Delta, Not a Total (available 2026-11-23).
If your top-CPU query has turned up in one of these sources and not another, I’d like to hear about it. Find me on Bluesky or LinkedIn.
References
- sys.dm_exec_query_stats (Transact-SQL) - Microsoft Learn. Rows are tied to the cached plan and removed with it, the data reflects only finished queries, total_worker_time is CPU in microseconds since compilation, and query_hash groups queries that differ only by literal values. ↩
- Query hints (Transact-SQL) - Microsoft Learn. RECOMPILE generates a temporary plan and discards it after the query completes. ↩
- sys.dm_exec_procedure_stats (Transact-SQL) - Microsoft Learn. One row per cached stored procedure plan, removed when the procedure leaves the cache, with total_worker_time in microseconds. ↩
- ALTER DATABASE SCOPED CONFIGURATION (Transact-SQL) - Microsoft Learn. CLEAR PROCEDURE_CACHE clears the plan cache for the database. ↩
- sys.query_store_runtime_stats (Transact-SQL) - Microsoft Learn. avg_cpu_time is in microseconds per interval, and execution_type distinguishes regular, client-aborted and exception-aborted executions. ↩
- ALTER DATABASE SET options (Transact-SQL) - Microsoft Learn. Queries inside stored procedures are always captured under ALL, AUTO or CUSTOM, QUERY_CAPTURE_MODE AUTO captures queries based on execution count and resource use and is the default from SQL Server 2019, and DATA_FLUSH_INTERVAL_SECONDS controls the asynchronous write of Query Store data to disk. ↩
- Monitor performance by using the Query Store - Microsoft Learn. Query Store is off by default in SQL Server 2016 to 2019 and on by default for new databases from SQL Server 2022. ↩
- sys.dm_exec_requests (Transact-SQL) - Microsoft Learn. cpu_time is the CPU used by the request in milliseconds. ↩
- sys.dm_os_ring_buffers (Transact-SQL) - Microsoft Learn. A ring buffer holds a fixed number of records, the record column is not supported unless described in the official documentation or used as directed by Microsoft, and SQL Server 2025 adds a create_time column. ↩