SQL Server 2008 : Index analysis (part 3) - Identifying index fragmentation
3. Identifying index fragmentation
Indexes, like any other storage object, become fragmented over time through the course of normal insert, delete, and update activity. Identifying the level of fragmentation is a crucial component of a targeted maintenance plan.In this section, our focus is on identifying fragmentation levels, achieved using the sys.dm_db_index_physical_stats dynamic management function.
Figure 7. Database Engine Tuning Advisor recommendations are shown after workload analysis is complete.
One of the columns returned from this DMF is
avg_fragmentation_in_percent. This indicates the percentage of pages
that are out of order, meaning the logical and physical ordering of
index pages no longer match, incurring additional disk activity when
scanning/seeking.
The code displayed in listing 3 uses the sys.dm_db_index_physical_stats function to return index fragmentation levels for all tables and indexes in the AdventureWorks database.
Example 3. Displaying index fragmentation
The output of this command, as shown in figure 8, is one row for each index in the database, with the avg_fragmentation_in_percent column ordered descending to list the most fragmented indexes first. This list will include clustered indexes, which indicates the level of fragmentation of the table itself.
In previous versions of SQL Server, we used the DBCC SHOWCONTIG command to retrieve, among other things, the logical scan fragmentation value for a given index. While this command is still available, the sys.dm_db_index_physical_stats function is the preferred method. One of the limitations with DBCC SHOWCONTIG is its lack of accuracy when analyzing storage spanning multiple files. In contrast, the sys.dm_db_index_physical_stats function has no such limitations and is therefore the recommended method for index fragmentation analysis.
Figure 8. Index fragmentation levels for AdventureWorks tables
Having covered a number of important index-analysis techniques, let's move on now to the actual index-maintenance tasks required to keep our databases performing well.