Cleaning up unused indexes can help improve the performance of DML queries in your database. To collect and analyze index usage statistics, follow these steps:
- Create a table to store index usage data:
CREATE TABLE dbo.IndexUsageStats (
CaptureDate DATE,
DatabaseID INT,
ObjectID INT,
IndexID INT,
UserSeeks BIGINT,
UserScans BIGINT,
UserLookups BIGINT,
UserUpdates BIGINT
);
- Schedule a daily job to capture index usage data:
INSERT INTO dbo.IndexUsageStats (
CaptureDate, DatabaseID, ObjectID, IndexID,
UserSeeks, UserScans, UserLookups, UserUpdates
)
SELECT
CAST(GETDATE() AS DATE),
DatabaseID, ObjectID, IndexID,
User_Seeks, User_Scans, User_Lookups, User_Updates
FROM sys.dm_db_index_usage_stats
WHERE DatabaseID = DB_ID(); -- Replace with the target database ID
- After collecting data for a month, analyze the index usage:
WITH IndexStatsSummary AS (
SELECT
ObjectID,
IndexID,
SUM(UserSeeks) AS TotalSeeks,
SUM(UserScans) AS TotalScans,
SUM(UserLookups) AS TotalLookups,
SUM(UserUpdates) AS TotalUpdates
FROM dbo.IndexUsageStats
WHERE CaptureDate > DATEADD(MONTH, -1, CAST(GETDATE() AS DATE))
GROUP BY ObjectID, IndexID
)
SELECT
OBJECT_NAME(i.object_id) AS TableName,
i.name AS IndexName,
s.TotalSeeks,
s.TotalScans,
s.TotalLookups,
s.TotalUpdates
FROM IndexStatsSummary s
JOIN sys.indexes i ON s.ObjectID = i.object_id AND s.IndexID = i.index_id
WHERE s.TotalSeeks = 0 AND s.TotalScans = 0 AND s.TotalLookups = 0
ORDER BY s.TotalUpdates DESC, OBJECT_NAME(i.object_id), i.name;
This query will show the indexes that haven't been used for reads (seeks, scans, or lookups) in the past month and are ordered by the number of updates. These are potential candidates for disabling or dropping. However, before making any changes, consult with the application team to ensure that these indexes are not needed for any specific use cases or reporting purposes.
Keep in mind that this analysis assumes that your workload is representative of typical usage during the month. If there are any unusual activities or ad-hoc queries that may impact index usage, consider extending the analysis period or investigate those activities separately. Always test the impact of disabling or dropping indexes in a non-production environment before making changes in production.