- Community Pick
As more data is needing to use (or creates) non-contiguous space, then it can cause fragmentation. When that happens, a read or search has to jump around the database to retrieve the requested data. There is a lot more to it, but that should give you an idea.
This is a sql script I wrote based off this MSDN article : http://msdn.microsoft.com/
The above article contains a script the will rebuild/reorg indexes above 10% fragmented on just the current database. I took the script much further, see details below.
This script will:
- rebuild all indexes >30% fragmented
- regorg all indexes >10% fragmented and <30% Fragmented
- The script will run on all databases on the entire sql instance dynamically using a
cursor based of list from master.sys.databases
- The script excludes the following databases
('master','tempdb','msdb',
The script runs great as a sql server agent job and can completely replace the standard sql server maintenance plan job the reorg/rebuilds all indexes regardless of fragmentation.
SQL REBUILD / REORG SCRIPT:
In Conclusion:
- In most cases/environments this script only needs to be run once per week.
- I schedule it to run every Saturday night/Sunday Morning at 12:30AM
- I like to create three steps in my sql agent job
#1 Report of Index Fragmentation prior to reorg/rebuild (I included a copy of my report script article)
#2 The actual Reorg/Rebuild Step
#3 Report of Index Fragmentation after to reorg/rebuild (I included a copy of my report script at bottom of article)
Keep in mind you may see some indexes that stay over 30% fragmented. This is most likely due to the way sql server creates objects. These particular objects are probably really small. When they are 1st created the object has a preallocate amount of free space in it which can skew the results in "sys.dm_db_index_physical_
You really need to understand your own data and decide if fragmentation is hurting performance. In an environment where you do have the luxury of running a "maintenance" job over the weekend, then there should be no reason not to do the required housekeeping. If you dont, then you do need to plan your time more carefully, because some of the above tasks can take a while to run.
Your best place to start is with the "report" script shown below. It will highlight those indexes which may be causing you problems. Remember check those row counts (or page counts) to see if it is significant enough for you to worry about.
BEFORE/AFTER REPORT SQL SCRIPT:
So, hope you find these scripts useful, and please check / test first and make sure your own maintenance solution works well for you in your environment.