Skip to content

Instantly share code, notes, and snippets.

@Dreyer
Created July 3, 2017 17:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Dreyer/8016e655f5b62230d762d1e2e2bac5ae to your computer and use it in GitHub Desktop.
Save Dreyer/8016e655f5b62230d762d1e2e2bac5ae to your computer and use it in GitHub Desktop.
Display database fragmentation for each table.
-- USE AdventureWorks;
SELECT
s.name AS 'sys_schema',
t.name AS 'sys_table',
i.name AS 'sys_index',
x.alloc_unit_type_desc,
x.avg_fragmentation_in_percent,
x.page_count
FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, NULL) x
INNER JOIN sys.tables t ON t.object_id = x.object_id
INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
INNER JOIN sys.indexes i ON i.object_id = x.object_id AND x.index_id = i.index_id
WHERE x.database_id = DB_ID()
ORDER BY x.avg_fragmentation_in_percent DESC;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment