Check Fragmentation Levels

Fragmentation levels.  Look for the pages count over 1,000 clause.


/*
DESCRIPTION:
Check fragmentation levels
 
CONFIGURATION
None

Author: Miguel Quintana

Compatibility list:
MSSQL2005
MSSQL2008

Does not work
MSSQL2000
 
*/

 USE yourdatabase

SELECT t.name as TableName, b.name as IndexName, b.index_id, ps.avg_fragmentation_in_percent, PAGE_COUNT AS PageCounts
, STATS_DATE( b.object_id , b.index_id ) AS LastUpdatedDate
FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, NULL) AS ps
INNER JOIN sys.indexes AS b ON ps.OBJECT_ID = b.OBJECT_ID
INNER JOIN sys.tables AS t on ps.OBJECT_ID = t.OBJECT_ID
AND ps.index_id = b.index_id
WHERE 1=1
and ps.database_id = DB_ID()
and page_count > 1000        -- ignore small tables
and b.index_id > 0            -- ignore heaps
and ps.avg_fragmentation_in_percent > 10  -- ignore small fragmentation
ORDER BY t.name, b.name

If receives error: Msg 102, Level 15, State 1, Line 2 Incorrect syntax near (. you will have to fill in with the actual Database id and plug in that value. See below


USE [yourdatabase]
SELECT DB_ID() AS [Database ID];
GO
 

Leave a Reply

Your email address will not be published. Required fields are marked *