
Explanation of How to Defragment All Indexes in a Database in SQL Server
Over time, indexes in SQL Server become fragmented due to frequent INSERT
, UPDATE
, or DELETE
operations. Fragmentation reduces performance by increasing disk I/O. To improve performance, indexes should be reorganized (if mildly fragmented) or rebuilt (if heavily fragmented).
You can use a script to automatically detect and fix fragmentation for all indexes in a database.
Example Script:
- DECLARE @TableName NVARCHAR(128);
- DECLARE @SQL NVARCHAR(MAX);
- -- Cursor to go through each table
- DECLARE TableCursor CURSOR FOR
- SELECT QUOTENAME(SCHEMA_NAME(o.schema_id)) + '.' + QUOTENAME(o.name)
- FROM sys.objects o
- WHERE o.type = 'U';
- OPEN TableCursor;
- FETCH NEXT FROM TableCursor INTO @TableName;
- WHILE @@FETCH_STATUS = 0
- BEGIN
- SET @SQL = '
- DECLARE @IndexName NVARCHAR(128);
- DECLARE @IndexId INT;
- DECLARE @Frag FLOAT;
- SELECT @IndexId = index_id,
- @Frag = avg_fragmentation_in_percent
- FROM sys.dm_db_index_physical_stats (DB_ID(), OBJECT_ID(''' + @TableName + '''), NULL, NULL, ''LIMITED'')
- WHERE index_id > 0;
- IF @Frag > 30
- ALTER INDEX ALL ON ' + @TableName + ' REBUILD;
- ELSE IF @Frag > 5
- ALTER INDEX ALL ON ' + @TableName + ' REORGANIZE;
- ';
- EXEC sp_executesql @SQL;
- FETCH NEXT FROM TableCursor INTO @TableName;
- END
- CLOSE TableCursor;
- DEALLOCATE TableCursor;
Explanation of Logic:
-
> 30% fragmentation →
REBUILD
the index (more effective but uses more resources). -
5%–30% fragmentation →
REORGANIZE
the index (lightweight). -
< 5% fragmentation → No action needed.
Conclusion:
This script helps automatically defragment all indexes in a database based on fragmentation level. Regular maintenance like this ensures faster query performance and more efficient disk usage. It's a best practice to schedule this during low-usage hours or as part of weekly maintenance.
Post Comment
Your email address will not be published. Required fields are marked *