Skip to content

Instantly share code, notes, and snippets.

@richardbasile
Created February 16, 2018 14:35
Show Gist options
  • Save richardbasile/a0fe1de7ec5334dd47f42258e3302e77 to your computer and use it in GitHub Desktop.
Save richardbasile/a0fe1de7ec5334dd47f42258e3302e77 to your computer and use it in GitHub Desktop.
SQL Server - Index Fragmentation
SELECT t.name as table_name, i.name as index_name, s.index_type_desc, s.avg_fragmentation_in_percent, s.page_count
FROM sys.dm_db_index_physical_stats (
DB_ID('<db name>')
, NULL --OBJECT_ID('dbo.<table name>')
, NULL
-- NULL to view all indexes;
-- otherwise, input index number
, NULL -- NULL to view all partitions of an index
, NULL -- 'DETAILED') as s
join sys.indexes i on i.object_id = s.object_id and i.index_id = s.index_id
join sys.tables t on t.object_id = s.object_id
where avg_fragmentation_in_percent > 30
and page_count > 1000
order by 1, 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment