SQL Scripts: How To Find Index Fragmentation

This is the first post in an ongoing SQL Scripts series, in which I list useful queries that I use in my day to day database administration.

What Is Index Fragmentation?

Over time, as records are inserted, updated, and deleted, your tables and indexes become fragmented.  This fragmentation can lead to poor performance of not only your SELECT queries, but also your INSERT, UPDATE, and DELETE operations.

How Do I Find Index Fragmentation?

Index fragmentation can be found by querying the built in sys.dm_db_index_physical_stats DMV. To get readable, useful information you’ll also need to join your query to other DMVs such as sys.indexes and sys.tables.  Below is a simple query that will provide a list of indexes, fragmentation percentage, and record counts for each table in a database.

The above query is database specific.  If you want to run it on every user database on your server, simply replace DB_ID() with NULL in the call to sys.dm_db_index_physical_stats.

 

(Visited 3,209 times, 1 visits today)

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.