Performance 06: index fragmentation

Run it in the database: fragmentation of every index over 1000 pages, using the light LIMITED scan. Read-only, changes nothing. Tested on SQL Server 2017 and 2025.

-- 06_Index_Fragmentation.sql - run IN the database: fragmentation of indexes over 1000 pages (LIMITED scan, fairly light). Read-only.
SET NOCOUNT ON;
SELECT OBJECT_SCHEMA_NAME(ps.object_id) + N'.' + OBJECT_NAME(ps.object_id) AS [table], i.name AS [index], ps.index_type_desc,
       ps.partition_number, CONVERT(decimal(5,1), ps.avg_fragmentation_in_percent) AS fragmentation_pct, ps.page_count, i.fill_factor
FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, 'LIMITED') AS ps
JOIN sys.indexes AS i ON i.object_id = ps.object_id AND i.index_id = ps.index_id
WHERE ps.page_count > 1000 AND ps.index_id > 0
ORDER BY ps.avg_fragmentation_in_percent DESC;