Click here to Skip to main content
11,925,851 members (62,007 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


11 bookmarked

Find and fix fragmented indexes

, 6 Feb 2014 CPOL
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 2006, 2007
Visual Basic .NET

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 

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.

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