Click here to Skip to main content
13,257,276 members (47,883 online)
Click here to Skip to main content
Add your own
alternative version


11 bookmarked
Posted 6 Feb 2014

Find and fix fragmented indexes

, 6 Feb 2014
Rate this:
Please Sign up or sign in to vote.
Quick tip to allow you to identify indexes that could do with defragmentation


Over time SQL server indexes become fragmented as data are inserted and deleted from the tables they refer to. Identifying these and defragmenting them can improve your database performance

Using the code

Replace [databasename] with your database name and then run the following SQL:-

select object_name(a.object_id), , a.avg_fragmentation_in_percent,  
sys.dm_db_index_physical_stats(db_id(N'[databasename]'), DEFAULT, DEFAULT, DEFAULT, DEFAULT) as a
inner join
sysindexes as b
on a.object_id = 
and a.index_id = b.indid
order by a.avg_fragmentation_in_percent desc

Then, from the results set if any indexes are highly fragmented, run the FIX_SQL to repair them

Points of Interest

  This runs a lot faster on the database itself than from master in my experience.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Duncan Edwards Jones
Software Developer (Senior)
Ireland Ireland
C# / SQL Server developer
Microsoft MVP (Azure) 2017
Microsoft MVP (Visual Basic) 2006, 2007

You may also be interested in...

Comments and Discussions

SuggestionJust a few notes Pin
franop10-Feb-14 23:02
memberfranop10-Feb-14 23:02 
GeneralRe: Just a few notes Pin
Duncan Edwards Jones10-Feb-14 23:11
memberDuncan Edwards Jones10-Feb-14 23:11 
Both good points.

Rebuilding an index (even with ONLINE=ON) is quite high impact so factors like "when is the database least busy" and "should I restrict the number of cpus the rebuild takes (using DOP)" should be added to this too?

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.171114.1 | Last Updated 6 Feb 2014
Article Copyright 2014 by Duncan Edwards Jones
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid