fragmentation for indexes

February 28th, 2008 by Mr.M | No Comments »

This is the SQL statement I use to find what % of index are fragmented.


SELECT A.object_id
, A.index_id
, [name]
, Avg_Fragmentation_In_Percent
FROM sys.dm_db_index_physical_stats (db_id(), NULL,NULL, NULL, NULL) AS A
JOIN sys.indexes B WITH(NOLOCK)
ON A.Object_id = B.Object_id
AND A.Index_id = B.Index_id
WHERE [name] IS NOT NULL

If Avg_Fragmentation_In_Percent is > 5% and <= 30%; ALTER INDEX REORGANIZE.
If Avg_Fragmentation_In_Percent is > 30%; ALTER INDEX REBUILD WITH (ONLINE = ON)*.

* Rebuilding an index can be executed online or offline. Reorganizing an index is always executed online. To achieve availability similar to the reorganize option, you should rebuild indexes online (SQL BOL).

Leave a Reply

You must be logged in to post a comment.