How to Use TSQL to Monitor Index Fragmentation

The script I use to monitor fragmentation is a very slightly modified version of the one found here which gives me a little additional information and excludes a bunch of indexes I probably don’t care about:

SELECT OBJECT_NAME(ind.OBJECT_ID) AS TableName,
ind.name AS IndexName,indexstats.index_type_desc AS IndexType,indexstats.page_count AS [Page Count],
indexstats.avg_fragmentation_in_percent
FROM sys.dm_db_index_physical_stats(DB_ID(),NULL,NULL,NULL,NULL) indexstats
INNER JOIN sys.indexes ind
ON ind.object_id=indexstats.object_id
AND ind.index_id=indexstats.index_id
WHERE indexstats.avg_fragmentation_in_percent> 10
and indexstats.page_count>500
ORDER BY indexstats.avg_fragmentation_in_percent DESC

According to Paul Randall’s blog post on Where the Books Online Index Fragmentation Thresholds Come From, the generally accepted guidelines are to rebuild indexes larger than 1000 pages that have more than 30% fragmentation.  So in the query above I have trimmed out indexes with less than 500 pages and included page count in the output.  You can go to 1000 pages if you want, but I like to start with a more aerial view when I have to troubleshoot index fragmentation.  It’s also worth reorganising Indexes which are fragmented below 30% – according to the above article anywhere between 5 and 30% should be reorganised.

Paul also makes a really important point in the article quoted above, and that is that these numbers are made up to give us a starting point.  So use the script above freely, but don’t forget there are a lot of other factors involved in whether the indexes it returns are causing you problems, or your constant attempts to get them sitting nicely are actually doing nothing to improve your server performance and are just sucking up your time and effort.

SQL Saturday Christchurch – Are you high?

On 10th August we are running a community event called SQL Saturday. What is SQL Saturday? It’s an opportunity for you to get free training in various areas of SQL Server that is an extension of the work that we are doing with the SQL Server user group.

Amongst quite a good lineup of speakers I’ll be taking a session on High Availability and Disaster Recovery(Are you high? Can you recover?), running through the various options that you have natively available out of the box. I’ve been working with these alot recently – almost as if some major disaster has hit the city I live it and people are suddenly aware of the danger of keeping all your eggs in one basket.

Alongside Martin and myself we have a great cast of speakers lined up including David Curlewis(TradeMe), Brent McCracken(Kiwibank), and Microsoft MVP’s Dave Dustan and Argenis Fernandez. If SQL isn’t your bag, you can join the code camp guys and talk applications, but I’m assuming if you are reading this SQL IS your bag:)