Question

I see a potential missing index for a table but would like to first query all cached plans that have that specific missing index (so I can later test those queries after the new index is built). How do you do build such a query? Can sp_blitzcache help here?

Was it helpful?

Solution

This isn't foolproof by any means but as a rough sanity check you can use the following query that leverages the DMVs to filter on the cached plan text's table name and index name that you plan to index:

SELECT 
    PlanText.[dbid] AS DatabaseId,
    DB_NAME(PlanText.[dbid]) AS DatabaseName,
    CachedPlans.plan_handle AS PlanHandle, 
    OBJECT_NAME(PlanText.objectid) AS ObjectName, 
    CachedPlans.objtype AS ObjectType, 
    CachedPlans.refcounts AS CachedPlanReferenceCount, 
    CachedPlans.usecounts AS CachedPlanUseCount, 
    PlanText.[text] AS QueryText
FROM sys.dm_exec_cached_plans AS CachedPlans
CROSS APPLY sys.dm_exec_sql_text(CachedPlans.plan_handle) AS PlanText
WHERE PlanText.[text] LIKE '%YourTableName%'
    AND PlanText.[text] LIKE '%YourColumnToBeIndexed%'

This leverages the DMVs sys.dm_exec_cached_plans and sys.dm_exec_sql_text. Just replace the wildcard filters above with your table name and index. This will give you the actual query that the cached plan is for, so then you can re-test it after you create the index. I also included some potentially helpful columns like DatabaseName, CachedPlanReferenceCount (how many objects reference this cached plan), and CachedPlanUseCount (how many times this plan was used). So you could theoretically add an ORDER BY CachedPlanUseCount DESC clause to get the most popularly used queries too and prioritize your list.

One reason why this isn't perfect is if the query in the QueryText column contains a different column coincidentally with the same name as the one you're indexing, but from a different table, and therefor will be a false positive match.

OTHER TIPS

To do this reliably you will need to upgrade to SQL Server 2019 and use the brand new DMV

sys.dm_db_missing_index_group_stats_query

There is a sample query with the documentation, I just became aware of this yesterday on Erik's blog.

https://docs.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-db-missing-index-groups-transact-sql?view=sql-server-ver15

https://www.erikdarlingdata.com/sql-server/documentation-for-dm_db_missing_index_group_stats_query/

Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top