Find queries using index

31 Oct 2017

sql

Find queries using index. Initially used to detect queries that were using eager spooling

can be used for index optimization as well

SELECT
querystats.plan_handle,
querystats.query_hash,
SUBSTRING(sqltext.text, (querystats.statement_start_offset / 2) + 1,
(CASE querystats.statement_end_offset
WHEN -1 THEN DATALENGTH(sqltext.text)
ELSE querystats.statement_end_offset
END - querystats.statement_start_offset) / 2 + 1) AS sqltext,
querystats.execution_count,
querystats.total_logical_reads,
querystats.total_logical_writes,
querystats.creation_time,
querystats.last_execution_time,
CAST(query_plan AS xml) as plan_xml
FROM sys.dm_exec_query_stats as querystats
CROSS APPLY sys.dm_exec_text_query_plan
(querystats.plan_handle, querystats.statement_start_offset, querystats.statement_end_offset)
as textplan
CROSS APPLY sys.dm_exec_sql_text(querystats.sql_handle) AS sqltext
WHERE
textplan.query_plan like '%missing%'
ORDER BY querystats.last_execution_time DESC
OPTION (RECOMPILE);
GO

further reading

https://littlekendra.com/2017/01/24/how-to-find-queries-using-an-index-and-queries-using-index-hints/ - How to Find Queries Using an Index
https://sqlperformance.com/2013/02/t-sql-queries/halloween-problem-part-1 - The Halloween Problem
https://www.red-gate.com/simple-talk/sql/learn-sql-server/operator-of-the-week-spools-eager-spool/ - Operator of the Week – Spools, Eager Spool
https://www.itprotoday.com/sql-server/divide-and-conquer-halloween - Divide and Conquer Halloween


Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.