Index maintenance is part of the DBA’s life. Surely you have a maintenance task for this somewhere running daily or weekly on your server. For the junior DBA, the rebuilding of indexes task will include a scheduled job that will reindex all indexes in the database. Imagine this task running on all your indexes and if your tables have a clustered index in them, which is most likely, this job is actually rewriting your entire database. This is a waste of precious resources on your server, unnecessary read/write activity and never mind the transaction log blowing out of proportions.
There is a more effective strategy for creating a maintenance plan for rebuilding fragmented indexes. The more effective approach would be to reindex only where needed and just leave the rest untouched. If it doesn’t need fixing, then don’t touch it at all.
First step would be to list all indexes in your database, like having an inventory of all indexes. You can query the DMV sys.dm_db_index_physical_stats for this. You may run a similar query below.
SELECT OBJECT_NAME(i.OBJECT_ID) AS TableName,
i.name AS IndexName,
iss.avg_fragmentation_in_percent AS FragmentationPercent
FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, NULL) iss
INNER JOIN sys.indexes i ON i.object_id = iss.object_id AND i.index_id = iss.index_id
ORDER BY iss.avg_fragmentation_in_percent DESC
Now that you have a gauge of how fragmented your indexes are, basing from the results of the query above, you can use your better judgement on which indexes to REBUILD or REORGANIZE and rewrite your maintenance task where applicable. To better understand the query results, if the avg_fragmentation_in_percent is less than 5%, then don’t touch it all. If the value is between 5% and 30% then run reorganize with the option ALTER INDEX REORGANIZE. If the avg_fragmentation_in_percent is above 30% then by all means run rebuild with the optionALTER INDEX REBUILD WITH (ONLINE=ON).
The (ONLINE=ON) option allows users to still use the index while the REBUILD task is ongoing. This feature is limited to enterprise edition of SQL Server 2005 and later only.
As a general rule, check your index fragmentation percentage daily or weekly then run your REBUILD or REORGANIZE task as needed only. This way you do not trigger unnecessary activity in your server and waste resources.
For more information on the guidelines, visit link http://support.microsoft.com/kb/2755960