Analyzing Query Performance and Resource Usage in SQL Server

sys.dm_exec_query_stats is a Dynamic Management View (DMV) in SQL Server that provides aggregate performance statistics for queries executed on the SQL Server instance. It contains information about the execution of queries, including how often they are executed and the resources they consume.


Key Columns:

  • sql_handle: A unique identifier for the SQL text associated with the query. This handle can be used to retrieve the actual SQL text from sys.dm_exec_sql_text.
  • execution_count: The number of times the query has been executed.
  • total_logical_reads: Total number of logical reads (pages read from the buffer cache) performed by the query.
  • total_logical_writes: Total number of logical writes (pages written to the buffer cache) performed by the query.
  • total_worker_time: Total amount of CPU time (in milliseconds) used by the query.
  • total_elapsed_time: Total time (in milliseconds) taken by the query to execute.
  • creation_time: The time when the query plan was created.
  • last_execution_time: The time when the query was last executed.


Use Case:

This DMV is useful for performance tuning and troubleshooting. It helps identify which queries consume the most resources and which might benefit from optimization. You can analyze execution patterns, resource usage, and query performance.


Example Query:

SELECT 
    qs.sql_handle, 
    qs.execution_count, 
    qs.total_logical_reads, 
    qs.total_logical_writes,
    qs.total_worker_time, 
    qs.total_elapsed_time,
    st.text AS sql_text
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
ORDER BY qs.total_worker_time DESC;