SQL SERVER – High Frequency Cached Query Counts and Statement Metrics

I measure High Frequency cached statements with decimal executions-per-second arithmetic. A customer wanted to identify the busiest queries.

A worn shuttle is inspected over its finite work area beside a fresh unworn tool.

SELECT TOP (20)
 SUBSTRING(t.text,(s.statement_start_offset/2)+1,
  ((CASE s.statement_end_offset WHEN -1 THEN DATALENGTH(t.text)
       ELSE s.statement_end_offset END-s.statement_start_offset)/2)+1) AS StatementText,
 s.execution_count,s.creation_time,
 s.max_elapsed_time/1000.0 AS MaxElapsedMs,
 s.total_elapsed_time/1000.0/NULLIF(s.execution_count,0) AS AverageElapsedMs,
 s.execution_count*1.0/NULLIF(DATEDIFF_BIG(millisecond,s.creation_time,SYSDATETIME())/1000.0,0) AS ExecutionsPerSecond
FROM sys.dm_exec_query_stats s CROSS APPLY sys.dm_exec_sql_text(s.sql_handle) t
ORDER BY ExecutionsPerSecond DESC;

My old formula divided execution_count by 1000 before dividing by seconds. Counts are not milliseconds, and integer division erased useful rates. This calculation divides executions by elapsed seconds since cache-entry creation.

Elapsed-time fields convert microseconds to milliseconds. Statement offsets isolate the individual statement instead of labeling the batch as one query. DATEDIFF_BIG requires SQL Server 2016 or later.

Eviction, recompilation and separate cached plans split or remove observations. A newly created entry can have no measurable interval, producing NULL. The average does not represent complete all-time history.

Use controlled deltas or retained workload evidence for a particular busy minute. Fetch plans for selected candidates. Retrieving every XML plan adds avoidable collection cost.

Related reading

A cache-lifetime rate is not an instantaneous rate, it is an average over the retained entry interval.

Published by Pinal Dave on SQLAuthority. More of my work at pinaldave.com.


Discover more from SQL Authority with Pinal Dave

Subscribe to get the latest posts sent to your email.

SQL Cache, SQL DMV, SQL Scripts, SQL Server
Previous Post
SQL SERVER – Stored Procedure Timing and Cached Measurements
Next Post
Index a Computed Column in SQL Server

Related Posts

1 Comment. Leave new

  • Hi Pinal
    for me, there is a simple typo, in your nice and useful query above.

    Instead of
    ISNULL(s.execution_count / 1000 /
    NULLIF(DATEDIFF(s, s.creation_time, GETDATE()), 0), 0) AS FrequencyPerSec

    I would use

    ISNULL(s.execution_count / 1. /
    NULLIF(DATEDIFF(s, s.creation_time, GETDATE()), 0), 0) AS FrequencyPerSec

    or something similar.
    Am I wrong?

    Thanks anyway for ypur work

    P.

    Reply

Leave a Reply

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

Fill out this field
Fill out this field
Please enter a valid email address.