dataiotech Labs
dbaguidedbaguideDBAdataxtoolsdataopsphere
Scripts Library/sqlserver/#44
Script #44
sqlserver
Maintenanceread-only (LIMITED modu)Min Version: 2008

SQL Server Index Fragmentation with Rebuild/Reorganize Advice

Measures fragmentation on large indexes and recommends rebuild or reorganize. Lets you plan maintenance windows without wasted work.

#fragmentation#rebuild#reorganize#index
sqlserver · sql
-- Mevcut veritabanında çalıştırın
SELECT TOP 50
       OBJECT_SCHEMA_NAME(ips.object_id) AS schema_name,
       OBJECT_NAME(ips.object_id)        AS table_name,
       i.name AS index_name,
       ips.avg_fragmentation_in_percent,
       ips.page_count,
       CASE WHEN ips.avg_fragmentation_in_percent >= 30 THEN 'REBUILD'
            ELSE 'REORGANIZE' END AS suggestion
FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, 'LIMITED') ips
JOIN sys.indexes i ON i.object_id = ips.object_id AND i.index_id = ips.index_id
WHERE ips.avg_fragmentation_in_percent > 10
  AND ips.page_count > 1000
  AND i.index_id > 0
ORDER BY ips.avg_fragmentation_in_percent DESC;
Operational Notes & Remediation Guidance

Verify in a staging environment prior to running in production. This is a read-only diagnostic query; it does not acquire exclusive locks.

Production Safety & Execution Standards
  • This script is designed for read-only diagnostics; it does not alter schema or modify data directly.
  • Prior to executing on production systems under high load, verify the target database version (Min. Version: 2008).
  • Exercise caution with mutating actions (e.g., terminating sessions or dropping indexes) referenced in the notes section.