I've written a query to look for indexes that are not used in the production environment in order to drop them, however I'm curious whether the last_user_update
column is an indication that the index was solely a maintenance overhead, in which case it would be good to drop it, or whether the index helped the performance of the insert/update/delete statement, in which case I wouldn't want to drop it. Below is the query I'd like to use:
DECLARE @DBInfo TABLE
( database_id int, object_id int, tablename nvarchar(200), indexname nvarchar(200), lastactivity datetime)
DECLARE @command VARCHAR(5000)
SELECT @command = 'Use [' + '?' + '] SELECT
database_id, o.object_id, o.name, i.name as indexname, max(lastactivity) as lastactivity
from (
select database_id, object_id, index_id, max(last_user_seek) as lastactivity from sys.dm_db_index_usage_stats
WHERE object_id > 1000
GROUP BY database_id, object_id, index_id
UNION ALL
select database_id, object_id, index_id, max(last_user_scan) as lastactivity from sys.dm_db_index_usage_stats
WHERE object_id > 1000
GROUP BY database_id, object_id, index_id
UNION ALL
select database_id, object_id, index_id, max(last_user_lookup) as lastactivity from sys.dm_db_index_usage_stats
WHERE object_id > 1000
GROUP BY database_id, object_id, index_id
/*UNION ALL
select database_id, object_id, index_id, max(last_user_update) as lastactivity from sys.dm_db_index_usage_stats
WHERE object_id > 1000
GROUP BY database_id, object_id, index_id*/
) a
inner join sys.objects o on a.object_id = o.object_id
inner join sys.indexes i on i.object_id = a.object_id AND i.index_id = a.index_id
where database_id = db_id()
GROUP BY database_id, o.object_id, o.name, i.name
order by lastactivity'
INSERT INTO @DBInfo
(database_id, object_id, tablename, indexname, lastactivity)
EXEC sp_MSForEachDB @command
SELECT db_name(database_id) as dbname, tablename, indexname, lastactivity FROM @DBInfo
where lastactivity < dateadd(day, -15, getdate()) or lastactivity is null
order by db_name(database_id), tablename, indexname