Skip to content

Instantly share code, notes, and snippets.

@SBajonczak
Created December 15, 2021 11:35
Show Gist options
  • Save SBajonczak/820e1937a7980f24e46f6fec5622b6bd to your computer and use it in GitHub Desktop.
Save SBajonczak/820e1937a7980f24e46f6fec5622b6bd to your computer and use it in GitHub Desktop.
Insights of Index Fragmentation
SELECT S.name as 'Schema',
T.name as 'Table',
I.name as 'Index',
DDIPS.avg_fragmentation_in_percent,
DDIPS.page_count
FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, NULL) AS DDIPS
INNER JOIN sys.tables T on T.object_id = DDIPS.object_id
INNER JOIN sys.schemas S on T.schema_id = S.schema_id
INNER JOIN sys.indexes I ON I.object_id = DDIPS.object_id
AND DDIPS.index_id = I.index_id
WHERE DDIPS.database_id = DB_ID()
and I.name is not null
AND DDIPS.avg_fragmentation_in_percent > 0
ORDER BY DDIPS.avg_fragmentation_in_percent desc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment