Automatically Rebuild or Reorg index based on fragmentation

The Attached SQL Query can be safely used for rebuilding or reorganizing all indexes in a particular database based on the fragmentation level.

Note: The script is currently set to perform offline index rebuild since online index rebuild is supported only in Enterprise edition SQL Server. Inorder to change it into online mode, add , ONLINE = ON statement along with

in line 100 in the attached script.

3203_AutoIndexRebuild2005andAbove (Click to download the script)


  1. Create a new job and insert the script as a step.
  2. Modify line numbers 39 and 40 and provide values wisely. If you feel like your indexes are heavily fragmented and most of the indexes are above 80% fragmented, It will be better to use higher value for @minfrag variable inorder to prevent this script from running too long.
  3. Update line 100 refering above note to make rebuild operation online for Enterprise Edition SQL Server.
  4. Trigger the job manually or schedule the job to run when there is least activity on the database.

Status update

This will be helpful when you feel like the script is running for long time and you need to see where the script is currently working. I have used two global temporary tables for the same. Table ##fraglist for seeing the fragmentation report for all the indexes and ##fragstatus for us to see where the script is currently working. The ##fragstatus table will have the list of index names which got rebuilt or reorganized. From that we can predict ETA for the whole process.

I will be releasing a newer version for this script soon in which we will get the information on the activity performed for each index. ie, if rebuild or reorg happened. Also I will keep an option to pause and start the activity from where it stopped last time.

Hope this helped. Thank you for reading.

Author: Sherbaz

Being a gadget enthusiast, He always felt good to try new programming languages and techniques. But never goes in-depth anywhere. was found when he tried php, html, javascript and mysql. Being an electronics engineer, he is also interested to build small gadgets and tools in embedded and digital electronics. As a profession, he handles microsoft sql server database and calls himself a database administrator

Leave a Reply