Query to track index fragmentation in a database
Query to track all the indexes with fragmentation in a database.
SELECT
OBJECT_NAME(object_id) AS TablelName
,(SELECT name FROM sys.indexes WHERE object_id = a.object_id and index_id = a.index_id) IndexName
,avg_fragmentation_in_percent
FROM sys.dm_db_index_physical_stats(DB_ID(‘<<DatabaseName>>’), NULL, NULL, NULL, NULL) a
WHERE avg_fragmentation_in_percent > 40
AND index_type_desc IN(‘CLUSTERED INDEX’, ‘NONCLUSTERED INDEX’)
ORDER BY avg_fragmentation_in_percent DESC
The <<DatabaseName>> needs to be filled with the database of your choice.

