DBA Scripts: Get Index Fragmentation Across Databases

🔧Part of the DBA-Tools Project, copy/paste SQL Server scripts and health checks.In: Maintenance & Automation › Index Maintenance

Reports and range scans have slowed over weeks, or you have just inherited a server and need to know whether anyone has been maintaining its indexes. This lists every index at 5% fragmentation or more in every online user database, in one result set, worst first across the server, so you can see where the problem sits before you plan a rebuild.


Why Index Fragmentation Matters

Fragmentation comes in two forms. Logical fragmentation means the physical page order no longer matches the logical index order, which hurts range scans and read-ahead. Page density problems mean pages are half empty, so the same data occupies more pages and the buffer pool carries the waste. Both accumulate naturally from inserts, updates and deletes; both are worse on indexes with random key patterns.

Whether fragmentation matters as much as it used to is a fair debate (on SSDs the scan penalty is smaller), but page density always matters, heavily fragmented large indexes still waste memory and I/O, and an instance where nothing has rebuilt indexes for a year almost always has other maintenance gaps too. A fragmentation sweep is as much a maintenance audit as a performance check.

  • Range scans and reports slow down as page order degrades
  • Half-empty pages inflate memory use and backup sizes
  • Fragmentation on big tables is a signal that index maintenance is not running

When to Run This Script

  • Routine SQL Server health checks
  • Taking over an unfamiliar instance, to audit the state of index maintenance
  • Before building or tuning index maintenance jobs, to size the problem
  • When reports or range-heavy queries degrade gradually over weeks
  • After large data loads, archiving runs, or bulk deletes

The Script

Run the following script against your SQL Server instance.

✓ Verified
  • Tested on: SQL Server 2025 (RTM CU8) 17.0.4075.5, Windows lab instance
  • Last verified: 2026-11-20 (re-run on the lab instance; the screenshot is from it)
  • Permissions: sysadmin, or access to every online user database plus VIEW DATABASE STATE and VIEW DEFINITION in each (server-wide: CONNECT ANY DATABASE, VIEW SERVER STATE and VIEW ANY DEFINITION)
  • Safety: read-only, impact medium
/*
Script Name : Get-IndexFragmentationAcrossDatabases
Category    : performance-troubleshooting
Purpose     : Check index fragmentation across all user databases in one result set, worst first, for maintenance planning.
Author      : Peter Whyte (https://sqldba.blog/dba-scripts-get-index-fragmentation-across-databases/)
Requires    : VIEW DATABASE STATE and VIEW DEFINITION in each user database (server-wide: CONNECT ANY DATABASE
              + VIEW SERVER STATE + VIEW ANY DEFINITION). Databases you cannot open are skipped and listed
              in the Messages tab, not errored. Without VIEW DEFINITION a database returns no rows and no error.
*/
-- SAFE:ReadOnly
-- IMPACT:Medium
SET NOCOUNT ON;
SET QUOTED_IDENTIFIER ON;

IF OBJECT_ID('tempdb..#Frag') IS NOT NULL DROP TABLE #Frag;

CREATE TABLE #Frag (
    database_name SYSNAME NOT NULL,
    schema_name SYSNAME NOT NULL,
    table_name SYSNAME NOT NULL,
    index_name SYSNAME NULL,
    avg_fragmentation_percent DECIMAL(5,2) NOT NULL,
    page_count BIGINT NOT NULL
);

DECLARE @db SYSNAME;
DECLARE @sql NVARCHAR(MAX);

DECLARE frag_cur CURSOR FAST_FORWARD FOR
    SELECT name FROM sys.databases
    WHERE state_desc = 'ONLINE'
      AND database_id > 4
    ORDER BY name;

OPEN frag_cur; FETCH NEXT FROM frag_cur INTO @db;
WHILE @@FETCH_STATUS = 0
BEGIN
    IF HAS_DBACCESS(@db) = 1
    BEGIN
        SET @sql = N'USE ' + QUOTENAME(@db) + N';
        INSERT INTO #Frag
        SELECT
            DB_NAME(),
            s.name,
            o.name,
            i.name,
            ROUND(ips.avg_fragmentation_in_percent, 2),
            ips.page_count
        FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, ''LIMITED'') AS ips
        INNER JOIN sys.indexes AS i
            ON ips.object_id = i.object_id
           AND ips.index_id = i.index_id
        INNER JOIN sys.objects AS o
            ON i.object_id = o.object_id
        INNER JOIN sys.schemas AS s
            ON o.schema_id = s.schema_id
        WHERE o.is_ms_shipped = 0
          AND ips.page_count > 0
          AND ips.alloc_unit_type_desc <> ''INTERNAL''
          AND ips.avg_fragmentation_in_percent >= 5.0;';
        BEGIN TRY EXEC sys.sp_executesql @sql; END TRY
        BEGIN CATCH PRINT 'Skipped ' + @db + ': ' + ERROR_MESSAGE(); END CATCH;
    END
    ELSE
        PRINT 'Skipped ' + @db + ': no access.';
    FETCH NEXT FROM frag_cur INTO @db;
END;
CLOSE frag_cur; DEALLOCATE frag_cur;

SELECT
    database_name,
    schema_name,
    table_name,
    index_name,
    avg_fragmentation_percent,
    page_count
FROM #Frag
ORDER BY avg_fragmentation_percent DESC, page_count DESC;

DROP TABLE #Frag;
SSMS results grid from Get-IndexFragmentationAcrossDatabases: one result set across every user database, indexes at 5 percent fragmentation or more, worst first

It loops the online user databases with a cursor, collects the rows into a temp table, and returns one result set across every database, sorted by fragmentation and then page count, worst first. A database with nothing at 5% or above adds no rows. OFFLINE databases are skipped; read-only databases are included. A database the login cannot open is skipped and named in the Messages tab (Skipped <database>: ...), so the rest of the sweep still returns.

It reads sys.dm_db_index_physical_stats (MS Docs) in LIMITED mode, which reads only the pages above the leaf level and takes an Intent-Shared table lock, not a scan of the data. Large databases take longer, so time the first run out of hours.


How To Run From The Repo

Clone DBA Tools, initialize and run the script:

# Clone dba-tools repo:
git clone https://github.com/peterwhyte-lgtm/dba-tools

# Initialize environment:
cd dba-tools

.\Initialize-Environment.ps1

# Sweep index fragmentation across all user databases:
.\run.ps1 Get-IndexFragmentationAcrossDatabases

# To run against a remote sql server:
.\run.ps1 Get-IndexFragmentationAcrossDatabases -ServerInstance SQLSERVER01

This script lives in the repo at:


Example Output

The whole of one run on the lab instance: 4 rows, all from one lab database, in one grid, worst first.

Get-IndexFragmentationAcrossDatabases in SSMS: 11 indexes worst first, Perfmon at 41 percent across 1,928 pages

Four of these rows earn a decision, the DBAMonitor collector tables over 1,000 pages: Perfmon at 41% across 1,928 pages is the rebuild case, StorageIO at 27% and WaitStats at 20% are reorganize candidates if the queries that read them have slowed, and QueryStore at 5% across 4,846 pages can be left alone. The other rows run as high as 92% but are tables of 2 to 118 pages, where the percentage is noise. On any server the rows worth a decision are the ones over 1,000 pages: over 30% is the rebuild case, and 5% to 30% is the reorganize case.

The same index name on 2 rows is 2 partitions: the script returns one row per partition and no partition number. Rebuilding a small index rarely clears it either; on an earlier lab run an 8 page index went from 87.5% to 16.67%, still on the list.


Understanding the Results

page_count
The size of the index in 8 KB pages, per partition. It decides whether the percentage matters. MS Docs gives no page number, but it does say that rebuilding or reorganizing small indexes usually does not reduce their fragmentation.Act when it is over about 1,000 pages, the usual community floor. Below that, skip the row: this script applies no floor of its own, so every small index at 5% or more is listed.
avg_fragmentation_percent
Logical fragmentation for an index (leaf pages out of order), extent fragmentation for a heap. LIMITED mode cannot measure page density, so a half-empty table never shows up: a lab heap with every other row deleted read 0% fragmentation at 47.7% page density.Act when a large index is over 30% (rebuild) or between 5% and 30% (reorganize) and the queries that scan it have slowed. Those are the traditional starting points; MS Docs says maintenance decisions should not rest on fixed thresholds alone.
index_name
NULL is a heap, a table with no clustered index. The same name on 2 rows is 2 partitions of one index.
database_name
The database each row came from. One grid covers every online user database the login could open; a database with no rows has nothing at 5% or more, or the login cannot see its tables. Databases it could not open are listed in the Messages tab as Skipped.Act when the grid is empty and you expected rows. The DMF needs VIEW DATABASE STATE, but the joins to sys.objects and sys.indexes also need VIEW DEFINITION, so a login without it gets no rows and no error; see metadata visibility (MS Docs).

How to Fix Fragmented Indexes

The one-off fix is a reorganize or rebuild of the specific large indexes the sweep surfaces, here 2 lab indexes from an earlier run:

-- 5% to 30%: always online, and stopping it keeps the progress made:
ALTER INDEX [PK_Customers] ON [dbo].[Customers] REORGANIZE;

-- Over 30%: fresh pages at your fill factor (ONLINE = ON needs Enterprise or Developer):
ALTER INDEX [PK_OrderLines] ON [dbo].[OrderLines]
REBUILD WITH (ONLINE = ON, SORT_IN_TEMPDB = ON);

On the lab the reorganize took PK_Customers from 22.28% to 0.42%, and the rebuild took PK_OrderLines from 99.18% to 1.59% and from 1,821 pages to 1,258, because the half-empty pages from the splits were packed back together.

The real fix is scheduled maintenance, so the sweep stops finding surprises: Generate Index Maintenance Jobs builds the Agent jobs. Before scheduling rebuilds, read the index maintenance strategy in MS Docs: a rebuild also updates statistics with a full scan, and much of the speed-up credited to rebuilds comes from that, which UPDATE STATISTICS gives you far more cheaply. Rebuilds are logged operations, so watch transaction log growth on the big ones.

This script is the survey: everything at 5% or more, with no size floor. For a shortlist already filtered to indexes of 1,000 pages or more at 10% or more, with a REORGANIZE or REBUILD column against each row, use Index Fragmentation.


Frequently Asked Questions

What is a good fragmentation percentage for SQL Server indexes?

The traditional starting points are under 5% leave it, 5% to 30% reorganize, and over 30% rebuild, on indexes over roughly 1,000 pages only. MS Docs no longer gives fixed numbers: it says to act when the queries that use the index have slowed, and to try a statistics update before a rebuild.

Does index fragmentation still matter on SSDs?

Less than it did on spinning disks, because out-of-order reads are cheaper. Low page density still matters everywhere though, since half-empty pages waste buffer pool memory and inflate I/O and backups regardless of storage speed.

How often should I check index fragmentation?

A weekly maintenance job with reorganize/rebuild thresholds handles the routine work. The instance-wide sweep earns its keep on new-to-you servers and health checks, where the question is whether maintenance has been happening at all.

Why does it return no rows and no error?

Either nothing is at 5% or more in any database, or the login cannot see the tables. The DMF needs VIEW DATABASE STATE, but the join to sys.objects and sys.indexes also needs VIEW DEFINITION. With VIEW SERVER STATE and CONNECT ANY DATABASE alone the joins see no tables, so every database adds no rows and raises no error; VIEW ANY DEFINITION server-wide fixes it. Check the Messages tab too, since a database the login could not open at all is listed there as Skipped.

What happens to a database the login cannot open?

It is skipped, not fatal. The script checks HAS_DBACCESS before each database and wraps the query in TRY/CATCH, so a database the login cannot open prints Skipped <database>: ... to the Messages tab and the sweep carries on. The grid then covers only the databases it could open, so read the Messages tab before trusting an all-clear. If you get Msg 916 and no rows at all, you are running an older copy of this script that ran every database in one batch.


Summary

One run, every database, worst indexes first: this sweep turns “is fragmentation a problem anywhere on the server” from a per-database chore into one run. The reading skill is simple but essential, always check the page count before reacting to a percentage.

I use it as an audit tool as much as a tuning tool. A long list of large fragmented indexes says the instance’s maintenance regime needs attention, and that finding usually matters more than any individual index in the output.


Related

You may also find these scripts useful:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *