Created
July 31, 2025 11:29
-
-
Save ycherkes/0c964330445739232c3272c1684939e0 to your computer and use it in GitHub Desktop.
Slow queries SQL 2016+ with query store enabled (added queryId)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ; | |
| WITH QueryWithPositions | |
| AS ( | |
| SELECT qs.creation_time | |
| ,qs.last_execution_time | |
| ,qs.total_physical_reads | |
| ,qs.total_logical_reads | |
| ,qs.total_logical_writes | |
| ,qs.execution_count | |
| ,qs.total_worker_time | |
| ,qs.total_elapsed_time | |
| ,st.TEXT | |
| ,qs.statement_start_offset | |
| ,qs.statement_end_offset | |
| ,PATINDEX('%-- #[0-9a-fA-F]%', st.TEXT) AS hash_pos | |
| ,q.query_id | |
| FROM sys.dm_exec_query_stats AS qs | |
| CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) st | |
| LEFT JOIN sys.query_store_query q ON qs.query_hash = q.query_hash | |
| ) | |
| SELECT query_id | |
| ,creation_time | |
| ,last_execution_time | |
| ,total_physical_reads | |
| ,total_logical_reads | |
| ,total_logical_writes | |
| ,execution_count | |
| ,total_worker_time | |
| ,total_elapsed_time | |
| ,total_elapsed_time / execution_count AS avg_elapsed_time | |
| ,CASE | |
| WHEN hash_pos > 0 | |
| THEN SUBSTRING(TEXT, hash_pos + 3, PATINDEX('%[ ' + CHAR(13) + CHAR(10) + ']%', SUBSTRING(TEXT, hash_pos + 3, 4000)) - 1) | |
| ELSE NULL | |
| END AS hash_tag | |
| ,TEXT | |
| ,SUBSTRING(TEXT, (statement_start_offset / 2) + 1, ( | |
| ( | |
| CASE statement_end_offset | |
| WHEN - 1 | |
| THEN DATALENGTH(TEXT) | |
| ELSE statement_end_offset | |
| END - statement_start_offset | |
| ) / 2 | |
| ) + 1) AS statement_text | |
| FROM QueryWithPositions | |
| ORDER BY total_elapsed_time / execution_count DESC; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment