Today, I worked on a service request that our customer needs to monitor and optimize queries that can significantly impact performance. This includes both queries running in parallel and those that, although executed with a single thread (MAXDOP 1), have a high volume of executions. In this article, we will explain a query that helps us identify these two types of queries in an Azure SQL Database.
The provided SQL query uses Dynamic Management Views (DMVs) in SQL Server to group and analyze execution statistics for queries. Let's break down and explain each part of this query:
WITH QueryStats AS (
SELECT
query_hash,
SUM(total_worker_time) AS total_worker_time,
SUM(total_elapsed_time) AS total_elapsed_time,
SUM(execution_count) AS execution_count,
MAX(max_dop) AS total_dop
FROM
sys.dm_exec_query_stats
GROUP BY
query_hash
)
SELECT
qs.query_hash,
qs.execution_count,
qs.total_worker_time,
qs.total_elapsed_time,
qs.total_dop,
SUBSTRING(st.text,
(qs_statement.statement_start_offset/2) + 1,
((CASE qs_statement.statement_end_offset
WHEN -1 THEN DATALENGTH(st.text)
ELSE qs_statement.statement_end_offset
END - qs_statement.statement_start_offset)/2) + 1) AS query_text
FROM
QueryStats qs
CROSS APPLY
(SELECT TOP 1 *
FROM sys.dm_exec_query_stats qs_statement
WHERE qs.query_hash = qs_statement.query_hash) qs_statement
CROSS APPLY
sys.dm_exec_sql_text(qs_statement.sql_handle) AS st
ORDER BY
qs.total_worker_time DESC;
Common Table Expression (CTE): QueryStats
Main Query:
CROSS APPLY:
ORDER BY:
By identifying both types of queries, database administrators can take actions such as query optimization, indexing, or adjusting the degree of parallelism settings to improve overall database performance.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.