Wednesday, April 25, 2012

Finding out unused indexes


Check the readings according to dm_db_index_usage_stats.

WITH indexstats ([Table],[Index],[Reads],[Writes],[Rows])
AS ( SELECT usr.[name] + '.' + obj.[name] [Table],
ixs.[name] [Index] ,
usage.user_seeks + usage.user_scans + usage.user_lookups [Reads],
usage.[user_updates] [Writes],
(SELECT SUM(sp.[rows]) FROM sys.partitions sp
WHERE usage.OBJECT_ID = sp.object_id
AND sp.index_id = usage.index_id) [Rows]
FROM sys.dm_db_index_usage_stats usage
INNER JOIN sys.indexes ixs
ON usage.[object_id] = ixs.[object_id]
AND ixs.[index_id] = usage.[index_id]
INNER JOIN sys.objects obj ON usage.[object_id] =
obj.[object_id] INNER JOIN sys.sysusers usr ON obj.[schema_id] = usr.[uid]
WHERE usage.database_id = DB_ID()
AND usage.index_id > 0
AND OBJECTPROPERTY(usage.[object_id], 'IsUserTable') = 1 )
SELECT * FROM indexstats WHERE Reads = 0 ORDER BY [Rows] DESC, [Index]

No comments: