Index fragmentation

On this page 7

Index fragmentation is the condition in which the pages of a database index no longer sit in logical key order on disk or are only partly filled with data, so that reading the index requires more input/output and more memory than its contents justify. In database performance work, it is one of the classic causes of gradual slowdown in tables that receive frequent inserts, updates and deletes.

The term covers two related problems: logical (external) fragmentation, where the physical page order diverges from the key order, and internal fragmentation, where pages contain large amounts of free space. Both arise from normal operation of B-tree indexes, and both are measured, tolerated or corrected rather than avoided entirely.

How index fragmentation develops

Index fragmentation develops mainly through page splits. A B-tree stores keys in sorted order across fixed-size pages, commonly 8 KB or 16 KB. When a new key must go into a page that is already full, the engine splits it: roughly half the rows move to a newly allocated page, which is often placed wherever free space exists rather than next to its logical neighbor.

Each split leaves two half-empty pages and breaks physical contiguity. Deletes add to the effect by leaving gaps that are reused only when a key in the same range arrives. Updates that grow variable-length columns can also force splits, and in multiversion engines such as PostgreSQL, obsolete row versions leave dead index entries until VACUUM removes them, a form of index bloat.

The table below lists the most common causes and the type of fragmentation each one produces.

CauseMechanismResulting fragmentation
Random key insertsNew keys land in full pages and trigger splitsLogical and internal
Mass deletesRows removed, pages left sparsely filledInternal
Growing row updatesWider rows no longer fit on the pageLogical and internal
Dead row versionsOld versions keep index entries until cleanupInternal (bloat)
Shrinking data filesPages moved to the end of the file are reorderedLogical
Causes of index fragmentation

Measuring index fragmentation

Index fragmentation is measured with two separate metrics that should be interpreted together. Logical fragmentation percentage counts leaf pages whose next page is not the physically next page. Page density, also called page fullness, shows how much of each page holds data. Most engines expose both through system views, for example sys.dm_db_index_physical_stats in SQL Server or the pgstattuple extension in PostgreSQL.

MetricWhat it showsHealthy rangeConcerning signal
Logical fragmentationOut-of-order leaf pagesUnder 10-30%Above 30% on large scanned indexes
Average page densityShare of page holding dataAbove 70-90%Below 60%
Page countSize of the indexStable relative to rowsGrowing faster than row count
Dead tuple shareObsolete entries awaiting cleanupLow single digitsPersistently above 20%
Key index fragmentation metrics

The widely quoted thresholds, reorganize above 5 to 10 percent and rebuild above 30 percent, are rules of thumb rather than laws. They also ignore small indexes, since an index of a few hundred pages fits in memory and its fragmentation has no measurable effect.

Why index fragmentation affects performance

The performance impact of index fragmentation depends on storage type and access pattern. Low page density always matters, because half-empty pages mean more pages to read and more space consumed in the buffer pool, which pushes other useful data out of memory. Logical disorder matters mostly for range scans on spinning disks, where out-of-order pages turn sequential reads into slow random seeks.

On solid-state storage, random reads cost little more than sequential ones, so logical fragmentation has a much smaller effect than it did on hard drives. Single-row lookups through an index seek touch only a few pages regardless of order. For this reason, many experienced administrators now focus on page density and index size rather than on the fragmentation percentage alone.

WorkloadImpact of logical disorderImpact of low density
Point lookups (index seeks)MinimalSmall
Range scans on hard disksHighHigh
Range scans on SSDLowModerate to high
Fully cached indexesNoneWasted memory only
Where fragmentation hurts and where it does not

Fixing and preventing index fragmentation

Fragmentation is corrected by reorganizing or rebuilding the index. A reorganize compacts and reorders leaf pages in place, runs online and can be interrupted, but it does not reduce the tree depth. A rebuild creates a fresh, fully ordered copy of the index; it is more thorough but needs extra space, generates heavy transaction logging and may lock the table unless an online option is available. PostgreSQL offers REINDEX CONCURRENTLY for the same purpose.

OptionWhat it doesCostBest for
ReorganizeCompacts and reorders leaf pagesLow, onlineModerate fragmentation
RebuildCreates a new ordered indexHigh log and space useHeavy fragmentation or bloat
Fill factor settingLeaves free space per pageLarger index on day oneIndexes with random inserts
Sequential keysInserts always append at the endPossible last-page contentionHigh-volume insert tables
Remediation options compared

Prevention is often more effective than repair. A fill factor of 80 to 90 percent leaves room for new keys and reduces page splits on indexes with random inserts, at the price of a larger index. Choosing ever-increasing keys, such as identity columns or time-ordered identifiers, instead of random UUIDs keeps inserts at the end of the index, although very high insert rates can then create lock contention on the last page.

Common misconceptions about index fragmentation

Index maintenance is frequently over-applied because the fragmentation percentage is easy to measure but poorly correlated with query speed on modern hardware. The following points summarize the most frequent errors.

  • Nightly rebuilds of every index waste I/O, inflate log and backup volumes and can slow replication without improving queries.
  • A rebuild that speeds up a query often helps because it refreshed statistics, not because pages became ordered.
  • Fragmentation on small indexes is irrelevant, since the whole index stays in memory.
  • Fill factor set too low permanently wastes space and memory on indexes that rarely split.
  • Shrinking data files after a rebuild reintroduces heavy logical fragmentation.

Explained without jargon

Think of an index as a large binder of alphabetically sorted cards. When a new card must go into a full sheet, the sheet is split and the overflow goes onto a new sheet at the back of the binder. Over time the binder is full of half-empty sheets in the wrong order.

Finding one card is still quick, but reading a whole letter range takes longer and the binder takes more shelf space. Reorganizing puts the sheets back in order. The main point is that fragmentation matters only when it makes real queries slower.

A typical use case

A logistics company stores shipment events in a table of about 400 million rows, with a nonclustered index on a random UUID column. Monthly reporting queries that scan a date range start taking 14 minutes instead of 5. Measurement shows average page density of 52 percent and logical fragmentation above 90 percent on a 60 GB index.

The database team rebuilds the index online with a fill factor of 90 percent, which reduces it to 34 GB, and then refreshes statistics. The report returns to about 5 minutes. To prevent a recurrence, new tables switch to time-ordered identifiers, and a weekly job reorganizes only indexes larger than 1,000 pages whose density falls below 70 percent.