Programming in MS SQL Server 2012

Index Defragmentation

The SQL Server Database Engine automatically maintains indexes whenever insert, update, or delete operations are made to the underlying data. Over time these modifications can cause the information in the index to become scattered in the database (fragmented).
Fragmentation exists when indexes have pages in which the logical ordering, based on the key value, does not match the physical ordering inside the data file. All leaf pages of an index contain pointers to the next and the previous pages in the index. This forms a doubly linked list of all index/data pages.
Ideally, the physical order of the pages in the data file should match the logical ordering. Overall disk throughput is increased significantly when the physical ordering matches the logical ordering of the data.
This leads to much better performance for certain types of queries. When the physical ordering does not match the logical ordering, disk throughput can become less efficient, because the disk head must move back and forth to gather the index pages instead of scanning forward in one direction.
Fragmentation affects I/O performance, but has no effect on performance of queries whose data pages reside in the SQL Server data cache. Heavily fragmented indexes can degrade query performance and cause your application to respond slowly.
The following example describes to find out average fragmentation percentage of all indexes in the dbo.Employee table.

-- Example 155 --


USE EBusiness




Find the average fragmentation percentage of all indexes in the dbo.Employee table.



SELECT a.index_id, name, avg_fragmentation_in_percent

FROM sys.dm_db_index_physical_stats (DB_ID(N'EBusiness'),

OBJECT_ID(N'dbo.Employee'), NULL, NULL, NULL) AS a

     JOIN sys.indexes AS b ON a.object_id = b.object_id AND a.index_id = b.index_id


Query Output Screen

The following table describes best method to correct the fragmentation based on degree of fragmentation.
avg_fragmentation_in_percent_value Corrective Statement
IF Fragmentation > 5% AND <= 30% ALTER INDEX REORGANIZE

* * * * *

Email Your Comment To AUTHOR