Wednesday, November 16, 2011

Determining the fragmentation of Indice

From http://www.sql-server-performance.com/2011/index-maintenance-performance/

SELECT
OBJECT_SCHEMA_NAME(FRAG.[object_id]) + '.' + OBJECT_NAME(FRAG.[object_id]),
SIX.[name],
FRAG.avg_fragmentation_in_percent,
FRAG.page_count
FROM
sys.dm_db_index_physical_stats
(
DB_ID(), --use the currently connected database
0, --Parameter for object_id.
DEFAULT, --Parameter for index_id.
0, --Parameter for partition_number.
DEFAULT --Scanning mode. Default to "LIMITED", which is good enough
) FRAG
JOIN
sys.indexes SIX ON FRAG.[object_id] = SIX.[object_id] AND FRAG.index_id = SIX.index_id
WHERE
--don't bother with heaps, if we have these anyway outside staging tables.
FRAG.index_type_desc <> 'HEAP' AND
(
--Either consider only those indexes that need treatment
(FRAG.page_count > @PageCount AND FRAG.avg_fragmentation_in_percent > @MinFragmentation)
OR
--or do everything when it is MaintenanceDay
@IsMaintenanceDay = 1
)
ORDER BY
FRAG.avg_fragmentation_in_percent DESC;


@PageCount: Default value is 128. Anything below this threshold we ignore. The benefits here do not justify the efforts.
•@MinFragmentation: This defaults to 10%. Anything below 10% is ignored. We couldn’t observe any significant performance hit with fragmentation levels < 10% given our workload.
•@IsMaintenanceDay: Once a week we have a maintenance window, in which we can maintain all indexes.

No comments: