How to Check Index Fragmentation in a SQL Server Database

When on a database's table frequently running INSERT, UPDATE or DELETE queries than we can see indexes on the particular table are fragmented and the SQL query may run slower as they may choose non-optimal execution plan. The below script can be used for checking how much percentages of an indexes gets fragmented on a database. so that we can rebuild or reorganize  the indexes.

SELECT OBJECT_NAME(ind.OBJECT_ID) AS TableName,
ind.name AS IndexName, indexstats.index_type_desc AS IndexType,
indexstats.avg_fragmentation_in_percent
FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, NULL) indexstats
INNER JOIN sys.indexes ind 
ON ind.object_id = indexstats.object_id
AND ind.index_id = indexstats.index_id
WHERE indexstats.avg_fragmentation_in_percent > 10--You can specify the percent as you want
AND ind.name is not null
ORDER BY indexstats.avg_fragmentation_in_percent DESC

 

Comments are closed