I’ve always found basic administration of SQL Server to be fairly straight-forward, but for a long while, I felt very uneasy about troubleshooting SQL Server performance issues. Any DBA knows that the most productive periods of learning arise when there are problems. For the past few months, I’ve been trying to track down a problem that I believe is hardware-related. Instead of keeping all my eggs in one basket, I’ve also been combing through DMV data to optimize the current database code.
One of the first things many people will look for are missing indexes. There are some great DMVs that will show you what indexes are suggested, but I wanted to know which queries those indexes were meant to help. I didn’t want to create an index on a table if the query it’s assisting runs infrequently or doesn’t have a direct benefit to a user. I decided to search the internet for suggestions on how to comb through the Plan Cache for query plans reporting a missing index.
I immediately found a script floating around to do just what I wanted. I’m not sure who the original author of this code is, but I thank them for helping me on my quest. The script was able to run through the plan cache and report to me the query text and the tables needing the index. However, I also wanted to know what stored procedures were responsible. Having the direct piece of code is helpful to know where to focus, but if it is being called by a stored procedure, it’s not helpful to know which one. Luckily, adding the required data was accomplished fairly easily by including more columns that were available in the DMVs.
It is important to set your query window to the context of the database you want to look at, so that the Object ID and Name resolutions will work properly. Any matching queries that are ad-hoc or not tied back to a stored procedure will just show NULL for these values. I’m also inserting the results into a table in MSDB instead of using a temp table like the original code. Depending on the size of your plan cache, this may take quite a while to run. My plan cache is 20GB and takes 30 minutes. I run it at night, but I have not observed any ill-effect on the database. In this example, I’ve limited the query plans to those with an execution count > 10. This removes the vast majority of the plans that are frequently recompiled. You will likely want to see everything at least once, so you can comment out the WHERE execution_count >10 as needed.
USE [dbName]; GO WITH XMLNAMESPACES (DEFAULT 'http://schemas.microsoft.com/sqlserver/2004/07/showplan') SELECT query_plan, objectId, -- Stored Procedure Object ID (Added) OBJECT_NAME(objectid) AS objectName, -- Stored Procedure Name (Added) n.value('(@StatementText)', 'VARCHAR(4000)') AS sql_text, n.value('(//MissingIndexGroup/@Impact)', 'FLOAT') AS impact, DB_ID(REPLACE(REPLACE(n.value('(//MissingIndex/@Database)', 'VARCHAR(128)'),'[',''),']','')) AS database_id, OBJECT_ID(n.value('(//MissingIndex/@Database)', 'VARCHAR(128)') + '.' + n.value('(//MissingIndex/@Schema)', 'VARCHAR(128)') + '.' + n.value('(//MissingIndex/@Table)', 'VARCHAR(128)')) AS OBJECT_ID, n.value('(//MissingIndex/@Database)', 'VARCHAR(128)') + '.' + n.value('(//MissingIndex/@Schema)', 'VARCHAR(128)') + '.' + n.value('(//MissingIndex/@Table)', 'VARCHAR(128)') AS statement, ( SELECT DISTINCT c.value('(@Name)', 'VARCHAR(128)') + ', ' FROM n.nodes('//ColumnGroup') AS t(cg) CROSS APPLY cg.nodes('Column') AS r(c) WHERE cg.value('(@Usage)', 'VARCHAR(128)') = 'EQUALITY' FOR XML PATH('') ) AS equality_columns, ( SELECT DISTINCT c.value('(@Name)', 'VARCHAR(128)') + ', ' FROM n.nodes('//ColumnGroup') AS t(cg) CROSS APPLY cg.nodes('Column') AS r(c) WHERE cg.value('(@Usage)', 'VARCHAR(128)') = 'INEQUALITY' FOR XML PATH('') ) AS inequality_columns, ( SELECT DISTINCT c.value('(@Name)', 'VARCHAR(128)') + ', ' FROM n.nodes('//ColumnGroup') AS t(cg) CROSS APPLY cg.nodes('Column') AS r(c) WHERE cg.value('(@Usage)', 'VARCHAR(128)') = 'INCLUDE' FOR XML PATH('') ) AS include_columns INTO msdb.dbo.Missing_Indexes FROM ( SELECT query_plan, objectid FROM ( SELECT DISTINCT plan_handle FROM sys.dm_exec_query_stats WITH(NOLOCK) WHERE execution_count > 10 -- Limit the plans as necessary to reduce run times (Added). ) AS qs OUTER APPLY sys.dm_exec_query_plan(qs.plan_handle) tp WHERE tp.query_plan.exist('//MissingIndex')=1 ) AS tab --(query_plan) CROSS APPLY query_plan.nodes('//StmtSimple') AS q(n) WHERE n.exist('QueryPlan/MissingIndexes') = 1 -- Trim trailing comma from lists UPDATE msdb.dbo.Missing_Indexes SET equality_columns = LEFT(equality_columns,LEN(equality_columns)-1), inequality_columns = LEFT(inequality_columns,LEN(inequality_columns)-1), include_columns = LEFT(include_columns,LEN(include_columns)-1)
I’m using a second query to join the missing index information back to the query execution information, instead of trying to handle it all at once. This just allows me to keep it a bit more modular and avoid making the code even more complicated than it is.
At this point, you can query the Missing_Indexes table as you wish, but you will need the following query to join it to the stats DMV.
SELECT DISTINCT ( ps.total_worker_time / ps.execution_count ) / 1000 AS AvgMS , ps.max_worker_time / 1000 AS MaxMS , ps.execution_count , mi.objectid , mi.objectName , /*mi.sql_text,*/ mi.impact , mi.object_id , mi.statement , mi.equality_columns , mi.inequality_columns , mi.include_columns FROM [msdb].[dbo].[Missing_Indexes] mi JOIN works.sys.dm_exec_procedure_stats ps ON mi.objectid = ps.object_id WHERE ( ( ps.total_worker_time / ps.execution_count ) / 1000 > 100 AND ps.max_worker_time / 1000 > 100 ) ORDER BY avgms DESC
There are obviously a number of ways you can run this second query, depending on your needs. I found it useful to remove the SQL_Text column and use a DISTINCT since there are likely to be a number of results. In my example, I limited the queries to those with an average execution time of > 100ms and also the max execution time of > 100ms. If dealing with a large amount of information, I would rather focus on the queries that take longer to run, but even fast-running queries can be tuned if they execute a large amount of times.
So by now you have a nice little list of stored procedures, and maybe some ad-hoc queries, that might need some investigation. Feel free to expand your filtering to exclude the ones with a lower impact or if you feel that the execution counts are not high enough to worry about. With this new technique, and the use of these helpful DMVs, I am much better suited to finding performance issues quickly.
As an example, a few days ago, a user emailed me with the infamous “hey the system is slow sometimes” email. Instead of letting them know that their information is less than helpful, I decided to just query the execution stats for the slowest running procedures. I quickly found the culprit — a stored procedure that averaged 9 seconds to run on a particular screen of the application. I was then able to see that it had a missing index, which I suggested to the developers.