Spot, measure, and troubleshoot long-running SQL Server statements with DMVs, Query Store, and Extended Events.
Slow queries often stem from missing indexes, outdated statistics, parameter sniffing, or inefficient joins. Pinpointing the real cause requires inspecting execution metrics and plans rather than guessing.
Use dynamic management views (DMVs) such as sys.dm_exec_query_stats to surface queries with the highest average or total duration. Joining dm_exec_sql_text returns the SQL statement for quick review.
SELECT TOP 20 qs.total_elapsed_time/qs.execution_count AS avg_ms, qs.execution_count, qs.total_logical_reads/qs.execution_count AS avg_reads, DB_NAME(st.dbid) AS db_name, st.text, qp.query_planFROM sys.dm_exec_query_stats qsCROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) stCROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) qpORDER BY avg_ms DESC;
Create an Extended Events session filtering duration > 2 seconds. This lightweight trace stores captured events in a ring buffer for immediate inspection with sys.fn_xe_file_target_read_file.
Turn on Query Store in production databases running SQL Server 2016+. It logs runtime stats per plan, allowing regressions to be detected and fixed by forcing stable plans.
Start with composite indexes covering join and filter columns. Verify effectiveness with actual execution plans; a reduced logical read count signals success.
Keep statistics current, write sargable predicates, avoid SELECT *, and monitor query performance regularly through automated jobs that alert when duration thresholds are exceeded.
Yes. Query Store uses minimal overhead (1-2% CPU) and provides invaluable historical data. Always size the max_store_size_mb and clean up policies.
Update daily for volatile tables or when row modifications reach ~20% of table size. Use UPDATE STATISTICS Products WITH FULLSCAN;
Compare multiple plans for the same query in Query Store. If plans differ greatly in cost, consider option(RECOMPILE) or optimized indexing.