Explanation to Defragment All Indexes in a Database

Explanation to Defragment All Indexes in a Database

In this detail how to generate and run a SQL Server script that could automatically identify and repair index fragmentation of all indexes within a database. Index fragmentation which is caused by the frequent updates of data can extensively result in the poor performance of a database. This granted by the script given isolates the degree of fragmentation, and re-ordering (in the case of low fragmentation) or recreates (in the case of high fragmentation) the indexes in order to attain the optimal level of performance.


Over time, indexes in SQL Server become fragmented due to frequent INSERTUPDATE, 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:

  1. DECLARE @TableName NVARCHAR(128);  
  2. DECLARE @SQL NVARCHAR(MAX);  
  3.   
  4. -- Cursor to go through each table  
  5. DECLARE TableCursor CURSOR FOR  
  6. SELECT QUOTENAME(SCHEMA_NAME(o.schema_id)) + '.' + QUOTENAME(o.name)  
  7. FROM sys.objects o  
  8. WHERE o.type = 'U';  
  9.   
  10. OPEN TableCursor;  
  11. FETCH NEXT FROM TableCursor INTO @TableName;  
  12.   
  13. WHILE @@FETCH_STATUS = 0  
  14. BEGIN  
  15.     SET @SQL = '  
  16.     DECLARE @IndexName NVARCHAR(128);  
  17.     DECLARE @IndexId INT;  
  18.     DECLARE @Frag FLOAT;  
  19.   
  20.     SELECT @IndexId = index_id,   
  21.            @Frag = avg_fragmentation_in_percent  
  22.     FROM sys.dm_db_index_physical_stats (DB_ID(), OBJECT_ID(''' + @TableName + '''), NULLNULL''LIMITED'')   
  23.     WHERE index_id > 0;  
  24.   
  25.     IF @Frag > 30  
  26.         ALTER INDEX ALL ON ' + @TableName + ' REBUILD;  
  27.     ELSE IF @Frag > 5  
  28.         ALTER INDEX ALL ON ' + @TableName + ' REORGANIZE;  
  29.     ';  
  30.       
  31.     EXEC sp_executesql @SQL;  
  32.     FETCH NEXT FROM TableCursor INTO @TableName;  
  33. END  
  34.   
  35. CLOSE TableCursor;  
  36. DEALLOCATE TableCursor;  



The script performs a check on all the user tables in database and examines the extent of fragmentation of each index. It re-establishes or re-constructs the indexes depending on the ratio of fragmentation.


1.Variable Declaration

  • @TableName: It stores the name of the table, which is being worked on.
  • @SQL: The SQL command generated dynamically is stored.

2. Cursor Creation

A new cursor called Table Cursor is defined which will be used to traverse all the user tables of the database. 
  • SELECT statement retrieves the schema name and the name of user tables.
  • QUOTENAME ensures that the schema and table names are quoted in a proper manner and at this, names containing special characters are given the right treatment.

3. Cursor Iteration

  • Cursor is opened and the initial name of table is loaded into the variable @TableName.
  •  The WHILE loop runs until further tables need to be processed (@@FETCH_STATUS = 0).

4. Dynamic SQL Generation of SQL.

Inside the loop, the script creates a dynamic SQL statement and puts it in charge of the variable @SQL.
In this dynamic SQL statement, it does the following:
  1. Declares variables to hold index information: @IndexName, @IndexId and @Frag.
  2. Executes a call to the dynamic management function (DMF), sys.dm_db_index_physical_stats, in order to see the fragmentation percentage (avg_fragmentation_in_percent) of each single index in the current table. Faster execution is described as limited sampling mode.
  3. Verifies the percentage of fragmentation (@Frag) and ascertains the need to execute either a REBUILD or a REORGANIZE operation:
  •  @Frag > 30 will result in the running of the statement ALTER INDEX ALL on + @TableName + rebuild; in the script. This reconstitutes every index on the table. Rebuilding uses more resources but it is more suited to heavily fragmented indexes.
  • In case @Frag > 5, the script will run the ALTER INDEX ALL ON ' + @TableName + ' REORGANIZE;. This reorganizes all indexes on a table. One is reorganizing, an light operation that performs well on indexes that are moderately fragmented.

5. Execution of Dynamic SQL

The dynamic SQL statement in sp_executesql stored procedure executes the saved SQL text in @SQL. This allows script to optimize index maintenance depending on the extent of fragmentation of an index.

6. Cursor Management

• Once the dynamic SQL is executed, the script pulls the next table name in cursor and loads in the variable @TableName.
• After all the tables are done, a cursor is closed and deallocated to free system resources.

Explanation of Logic:


    • > 30% fragmentation → REBUILDING an index, drops the current index and recreates it. It is more efficient when indexes are very fragmented and it is more resources-demanding, therefore it is also slower.

    • 5%–30% fragmentation → REORGANIZE the Index Reorganizing of an index implies that the particular leaf-nodes are reordered to reflect the logical order of the index. This is a lightweight operation, which can be conducted online and which is applicable on indexes that are moderately fragmented.

    • < 5% fragmentation → less than 5 % 0 action required Low fragmented indexes are those that cannot be maintained.

      Conclusion:

    This script is a routine that index-repair, on an automatic basis, all the indexes within a database according to their level of fragmentation. The frequent utilization of this script will facilitate queries to be faster and occupy less space on the hard drive. We should like to arrange the script such that it executes during off-peak time or on a weekly maintenance schedule such that it does not load the database to a crawl.

     

0 Comments

Post Comment

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