Skip to content

Instantly share code, notes, and snippets.

@umair-me
Last active June 29, 2020 16:46
Show Gist options
  • Save umair-me/92ec4e0e047ee58e06b0 to your computer and use it in GitHub Desktop.
Save umair-me/92ec4e0e047ee58e06b0 to your computer and use it in GitHub Desktop.
Check SQL table index fragmentation
SELECT OBJECT_NAME(ind.OBJECT_ID) AS TableName,
ind.name AS IndexName,
indexstats.index_type_desc AS IndexType,
indexstats.avg_fragmentation_in_percent ,
CONCAT('ALTER INDEX [', ind.name, '] ON [', OBJECT_NAME(ind.OBJECT_ID), '] REBUILD')
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 > 30
ORDER BY indexstats.avg_fragmentation_in_percent DESC
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment