Index-only scan

On this page 7

An index-only scan is a query execution strategy in which the database engine returns every requested column directly from an index, without fetching the corresponding rows from the base table. In databases, it is one of the most effective optimizations that indexing makes possible, because it removes the random heap or table lookups that usually dominate the cost of an ordinary index scan.

The strategy works only when the index contains all columns the query needs, both in the select list and in the filter, join and sort clauses. Engines that use multiversion concurrency control add a second condition: they must be able to confirm, without reading the row, that each index entry points to a row version visible to the current transaction.

How an index-only scan avoids table access

An index-only scan replaces the two-step pattern of a normal index lookup with a single traversal. In a standard index scan, the engine walks the B-tree to find matching keys and then follows each row pointer (a tuple identifier, row ID or clustering key) to the table to read the remaining columns. Each pointer can land on a different page, so a query that matches thousands of rows may trigger thousands of random page reads.

When the index already stores every referenced column, the second step is unnecessary. The engine reads the leaf pages of the index in key order, extracts the values and passes them up the plan. Because index leaf pages are densely packed and sorted, the access pattern is largely sequential and far fewer pages are touched.

The following table contrasts the steps performed by the main access paths for the same filtered query.

Access pathIndex pages readTable pages readTypical I/O pattern
Sequential scanNoneAll pagesSequential, full table
Index scanMatching rangeOne per matching row, often repeatedRandom
Bitmap index scanMatching rangeEach needed page once, in physical orderSemi-sequential
Index-only scanMatching rangeOnly when visibility is uncertainMostly sequential
Work performed by common access paths

Conditions the query planner checks

The query planner chooses an index-only scan only after confirming several structural and statistical conditions. The most important is column coverage: an index that contains every referenced column is called a covering index for that query, and without it the plan cannot be index-only.

Coverage can be achieved in two ways. A composite index places the extra columns in the key itself, which also makes them usable for sorting and range filtering. An included column (the INCLUDE clause in PostgreSQL and SQL Server) stores extra values only in the leaf level, keeping upper levels small while still enabling index-only retrieval.

RequirementWhat it meansConsequence if missing
Full column coverageEvery selected, filtered and sorted column is in the indexEngine must read the table
Index type supportThe access method can return stored valuesPlan not available for that index
Visibility informationEngine can verify row visibility without the heapExtra heap fetches per row
Favorable cost estimatePlanner expects fewer page reads than alternativesPlanner picks another path
Requirements for an index-only plan

Not every index type qualifies. B-tree indexes almost always support index-only retrieval, while some engines cannot return values from hash or GIN indexes because those structures store hashes or extracted tokens rather than original column values. Expression indexes may qualify only when the query uses exactly the indexed expression.

Visibility and the role of MVCC

In engines based on multiversion concurrency control, an index entry does not prove that its row is visible to the current snapshot. Index entries in PostgreSQL, for example, carry no transaction information, so a deleted or uncommitted row version can still have a live index entry until vacuum removes it.

PostgreSQL solves this with the visibility map, a compact structure holding one bit per heap page that marks pages where every tuple is visible to all transactions. During an index-only scan, the executor checks that bit; if it is set, the heap is skipped, and if it is not, the engine performs a heap fetch for that row. The EXPLAIN ANALYZE output reports these as Heap Fetches, and a high count signals that the scan is not truly index-only.

Other engines handle the problem differently, which changes how reliable the optimization is in practice.

EngineTerm usedVisibility mechanismPractical note
PostgreSQLIndex Only ScanVisibility map maintained by vacuumDepends on regular vacuuming
MySQL InnoDBCovering index (Using index)Page-level transaction ID check in secondary indexesClustered key is always included
SQL ServerCovering index seek or scanLocking or row versioning in the index itselfUses INCLUDE columns widely
Oracle DatabaseIndex fast full scan or range scanUndo-based read consistency on index blocksNo separate visibility structure
How major engines handle index-only retrieval

Designing indexes that enable index-only scans

Good index design starts from the most frequent and expensive queries, not from individual columns. The usual pattern is to put equality filter columns first, then range or sort columns, and to add the remaining selected columns either as trailing key columns or as included payload columns.

  • Avoid SELECT * in hot queries, because selecting all columns makes coverage practically impossible.
  • Prefer included columns for values that are only returned, keeping the key narrow and the tree shallow.
  • In InnoDB, remember that secondary indexes already contain the primary key, so it does not need to be added.
  • Check the plan with EXPLAIN after every change, because a single new column in a query can silently break coverage.

Every additional column carries a cost. Wider indexes consume more memory and disk, slow down inserts and updates, and can reduce the benefit of the index for other queries. The decision table below summarizes typical choices.

SituationRecommended approachReason
Hot read query selecting two or three columnsCovering index with INCLUDELarge I/O savings for small storage cost
Query returns many wide text columnsNormal index scanIndex would duplicate most of the table
Write-heavy table with frequent updatesMinimal key-only indexWrite amplification outweighs read gains
Aggregate such as COUNT over an indexed columnIndex-only scan on a narrow indexLeaf pages are smaller than heap pages
Choosing a strategy for frequent queries

Limitations and common misconceptions

The most common misconception is that an index-only plan in EXPLAIN guarantees zero table access. In PostgreSQL, tables with heavy update or delete churn may have few all-visible pages, so the scan can perform nearly as many heap fetches as an ordinary index scan. Aggressive autovacuum settings on such tables restore the benefit.

A second misconception is that a covering index always wins. For queries that return a large fraction of the table, a sequential scan can still be cheaper, and the planner may correctly reject the index-only path. Finally, an index-only scan does not remove index maintenance costs: every covered column must be updated in the index whenever it changes, which can disable optimizations such as heap-only tuple updates in PostgreSQL.

In everyday language

Think of a library catalog card that lists not only the shelf location of a book but also its author, year and page count. If all you want is the year a book was published, you can read it straight from the card and never walk to the shelf. An index-only scan works the same way: the database finds everything it needs in the index and skips the trip to the table.

The catch is that the card must hold every detail you ask for. Ask for one extra detail that is not on the card, and the database has to go to the shelf again. It also needs to be sure the card is up to date, which is why routine maintenance matters.

Seen in the real world

An online retailer runs a dashboard query thousands of times per minute that lists the order date and total for one customer’s last 50 orders. The orders table holds about 200 million rows in PostgreSQL, and the existing index on customer ID forced a heap fetch for every returned row, taking roughly 40 milliseconds per call under load.

The database team created an index on customer ID and order date with the total as an included column, and tuned autovacuum so the visibility map stayed current. EXPLAIN ANALYZE then showed an index-only scan with Heap Fetches near zero, and median latency fell to about 2 milliseconds. The trade-off was roughly 6 GB of extra index storage and slightly slower inserts, which the team judged well worth the read savings.