Created
December 19, 2024 19:48
-
-
Save petesql/e453993e44d41cdabbcd32c581f1f5f1 to your computer and use it in GitHub Desktop.
Show Unused Indexes SQL Server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- This query retrieves and suggests unused index information from the DMV (Dynamic Management Views) in SQL Server. | |
-- It identifies unused or rarely used non-clustered indexes and generates DROP INDEX statements for them. | |
SELECT TOP 25 | |
o.name AS ObjectName, | |
i.name AS IndexName, | |
i.index_id AS IndexID, | |
dm_ius.user_seeks AS UserSeek, | |
dm_ius.user_scans AS UserScans, | |
dm_ius.user_lookups AS UserLookups, | |
dm_ius.user_updates AS UserUpdates, | |
p.TableRows, | |
'DROP INDEX ' + QUOTENAME(i.name) + ' ON ' + QUOTENAME(s.name) + '.' + QUOTENAME(OBJECT_NAME(dm_ius.OBJECT_ID)) AS drop_statement | |
FROM | |
sys.dm_db_index_usage_stats dm_ius | |
INNER JOIN sys.indexes i | |
ON i.index_id = dm_ius.index_id | |
AND dm_ius.OBJECT_ID = i.OBJECT_ID | |
INNER JOIN sys.objects o | |
ON dm_ius.OBJECT_ID = o.OBJECT_ID | |
INNER JOIN sys.schemas s | |
ON o.schema_id = s.schema_id | |
INNER JOIN ( | |
SELECT SUM(p.rows) AS TableRows, p.index_id, p.OBJECT_ID | |
FROM sys.partitions p | |
GROUP BY p.index_id, p.OBJECT_ID | |
) p | |
ON p.index_id = dm_ius.index_id AND dm_ius.OBJECT_ID = p.OBJECT_ID | |
WHERE | |
OBJECTPROPERTY(dm_ius.OBJECT_ID, 'IsUserTable') = 1 | |
AND dm_ius.database_id = DB_ID() | |
AND i.type_desc = 'NONCLUSTERED' | |
AND i.is_primary_key = 0 | |
AND i.is_unique_constraint = 0 | |
ORDER BY | |
(dm_ius.user_seeks + dm_ius.user_scans + dm_ius.user_lookups) ASC; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment