Advertisement
bytecoded

Identifying Most Costly Unused Indexes

Oct 29th, 2019
369
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
SQL 1.39 KB | None | 0 0
  1. -- Create required table structure only.
  2. -- Note: this SQL must be the same as in the Database loop given in the following step.
  3. SELECT TOP 1
  4. DatabaseName = DB_NAME()
  5. ,TableName = OBJECT_NAME(s.[object_id])
  6. ,IndexName = i.name
  7. ,user_updates
  8. ,system_updates
  9. -- Useful fields below:
  10. --, *
  11. INTO #TempUnusedIndexes
  12. FROM sys.dm_db_index_usage_stats s
  13. INNER JOIN sys.indexes i ON s.[object_id] = i.[object_id]
  14. AND s.index_id = i.index_id
  15. WHERE s.database_id = DB_ID()
  16. AND OBJECTPROPERTY(s.[object_id], 'IsMsShipped') = 0
  17. AND user_seeks = 0
  18. AND user_scans = 0
  19. AND user_lookups = 0
  20. AND s.[object_id] = -999 -- Dummy value to get table structure.
  21. ;
  22. -- Loop around all the databases on the server.
  23. EXEC sp_MSForEachDB 'USE [?];
  24. -- Table already exists.
  25. INSERT INTO #TempUnusedIndexes
  26. SELECT TOP 10
  27. DatabaseName = DB_NAME()
  28. ,TableName = OBJECT_NAME(s.[object_id])
  29. ,IndexName = i.name
  30. ,user_updates
  31. ,system_updates
  32. FROM sys.dm_db_index_usage_stats s
  33. INNER JOIN sys.indexes i ON s.[object_id] = i.[object_id]
  34. AND s.index_id = i.index_id
  35. WHERE s.database_id = DB_ID()
  36. AND OBJECTPROPERTY(s.[object_id], ''IsMsShipped'') = 0
  37. AND user_seeks = 0
  38. AND user_scans = 0
  39. AND user_lookups = 0
  40. AND i.name IS NOT NULL -- Ignore HEAP indexes.
  41. ORDER BY user_updates DESC
  42. ; '
  43. -- Select records.
  44. SELECT TOP 10 * FROM #TempUnusedIndexes ORDER BY [user_updates] DESC
  45. -- Tidy up.
  46. DROP TABLE #TempUnusedIndexes
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement