For Turkish version, please click here.
When a table gets insert/update/delete, indexes are constantly fragmented. If the fragmentation pct. is high, indexes can reduce query performance. One of the important part of database maintenance is detecting fragmentation.
We can list the fragmentations by using Dynamic management views and functions on SQL Server. If the percentage is above 30%, rebuild the index (alter index indexName on tableName rebuild), if the percentage is between 10 and 30, reorganize the index (alter index indexName on tableName reorganize).
Don’t forget to rebuild the index with ONLINE option which makes the related table accessible while index maintenance process is being held on it ( …rebuild WITH (ONLINE = ON) ).
SELECT
OBJECT_NAME(i.OBJECT_ID) AS [Table Name],
i.name AS [Index Name],
ips.index_type_desc AS [Index Type],
ips.page_count AS [Page Count],
ips.avg_fragmentation_in_percent AS [Fragmentation Pct]
FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, NULL) ips
INNER JOIN sys.indexes i ON i.object_id = ips.object_id AND i.index_id = ips.index_id
where — you can comment out all 3 filters
i.is_disabled = 0 AND –only active indexes
ips.index_type_desc != ‘HEAP’ AND –only tables which have clustered index
ips.page_count > 40 –don’t include indexes which have small page count
ORDER BY [Fragmentation Pct] DESC