web 2.0

SQL Server Index Maintenance

One of the most important things you can do to improve performance in your database is to create and maintain indexes. The general rule of thumb is: if your indexes are less then 30% fragmented than you can run a DBCC INDEXDEFRAG else rebuild. However, an index rebuild is usually something that should be done after hours unless you have an enterprise edition license which will give you the ability to do an online rebuild. Anyway, I created this DMV which I use to check my indexes. It basically samples each table to get a percent fragmented value, I also filter the results by row count. If you have less than 1000 rows than a fragmented index is not a large concern.

SELECT
    OBJECT_NAME(DMV.object_id) AS TABLE_NAME
    ,SI.NAME AS INDEX_NAME
    ,avg_fragmentation_in_percent  AS FRAGMENT_PERCENT
    ,DMV.record_count
FROM
    sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, 'SAMPLED') as DMV
    LEFT OUTER JOIN SYS.INDEXES AS SI ON DMV.OBJECT_ID = SI.OBJECT_ID
    AND DMV.INDEX_ID = SI.INDEX_ID
WHERE
    avg_fragmentation_in_percent > 10
    AND index_type_desc IN('CLUSTERED INDEX', 'NONCLUSTERED INDEX')
    and DMV.record_count >= 2000
ORDER BY
    TABLE_NAME DESC

Tags: , ,

Comments are closed