skip to content

In PostgreSQL 18, how can a B-tree index on books(category_id, price) serve WHERE price < 5 with no condition on category_id, and when won't it?

level: seniorimportance: should knowfreq 46%

answer

  1. new in the 18 release
  2. an equality generated for the leading column
  3. repeated descents, one per value
  4. few distinct leading values
  5. a new line in EXPLAIN ANALYZE

basics

~20 s

PostgreSQL 18's skip scan treats the query as category_id = N AND price < 5 for each distinct category, repositioning once per value. It pays off when the leading column has few distinct values; with many, other plans win.

solid answer

~40 s

Before 18, a condition only on `price` could not narrow a scan of `(category_id, price)`: the planner either read the whole index, checking `price` in each entry, or scanned the table. PostgreSQL 18 adds **skip scan**: the B-tree generates an internal equality on `category_id` that matches every stored value, so the scan descends to the `price < 5` range inside each category and skips the rest. The planner picks it when it expects few distinct `category_id` values; the manual says no more than several hundred keeps such searches reasonably efficient. With many distinct values most of the index is read, and a sequential scan or a dedicated `price` index wins. In 18, `EXPLAIN ANALYZE` prints `Index Searches` for each index node, and each search also increments `pg_stat_all_indexes.idx_scan`.

code

sql · 7 lines
sql
CREATE INDEX books_category_price_idx ON books (category_id, price);

-- no condition on the leading column
EXPLAIN ANALYZE
SELECT book_id, title, price
FROM books
WHERE price < 5.00;

go deeper

for a junior

Recall that PostgreSQL 18 can use a multicolumn B-tree even without a condition on its first column, through skip scan.

for a middle

Explain the generated equality on the leading column, the repeated index searches, and why few distinct leading values are the condition for a win.

for a senior

Read Index Searches and buffers in an 18 plan, decide whether a dedicated index is still needed, and expect plan changes and idx_scan jumps after upgrading from 17.

for a principal

Fold skip scan into index strategy across mixed versions: an index set trimmed for 18 can regress on 17 replicas or during a staged upgrade.

## The rule before 18 A multicolumn B-tree is sorted by its first column, then by the second within each first-column value. On PostgreSQL 17 and earlier, only equality conditions on leading columns, plus a range on the first column without one, limit the part of the index that is scanned. A condition on a later column, such as `price < 5` against `(category_id, price)`, is still checked inside the index, which saves heap visits, but it does not shrink the scan. So the planner had two options: read **the entire index** or scan the table. The common shorthand that "a composite index is useless without its leading column" was always an overstatement, but in practice that whole-index read rarely won. ## How skip scan works PostgreSQL 18 adds the **skip scan** optimization to B-tree. For `WHERE price < 5` on `(category_id, price)`: 1. The scan generates an internal **dynamic equality** on `category_id` that matches every value present in the index. 2. It descends from the root to the first entry with the lowest `category_id` and `price < 5`. 3. It reads matching entries until prices reach 5 within that category. 4. It repositions with a new index search to the start of the next `category_id`, skipping all the expensive books in between. 5. It repeats until the categories run out. Each repositioning is one **index search**. The generated equality is only used when a later column has a condition from the query that it can combine with. Skip scan also works selectively inside a partly constrained scan: on `(a, b, c)` with `a = 5 AND b >= 42 AND c < 77`, the scan can jump from the end of each `b` group's `c < 77` entries to the next `b` value instead of reading the entries in between. Operator classes can provide a **skip support** function so the B-tree can step to the next possible value directly; `int4`, `int8`, `date`, `uuid` and several other types have one. Types without it are still eligible and use a fallback strategy. ## When the planner chooses it The planner costs repeated searches against the alternatives using its estimate of distinct values in the skipped column: | Distinct `category_id` values | Likely plan for `WHERE price < 5` | |---|---| | A handful to a few hundred | Skip scan on `(category_id, price)` | | Thousands or more | Most leaf pages hold matches somewhere; a sequential scan usually wins | | Any, with an index on `(price)` too | The dedicated index is the cheapest way to that range | The manual's guide is that if the leading column has no more than several hundred distinct values, skip scan makes searches on the second column reasonably efficient. The decision rests on the planner's statistics for the leading column, so stale estimates can make it choose badly. ## Seeing it in a plan `EXPLAIN ANALYZE` in 18 shows an **`Index Searches`** line on Index Scan, Index Only Scan and Bitmap Index Scan nodes: the total number of index descents across all loops of the node. For a skip scan over 30 categories, expect a value in that region rather than 1. The same count feeds statistics: every index search increments `pg_stat_all_indexes.idx_scan`, so after an upgrade to 18 that counter can climb much faster than the number of queries. ## What it changes for index design - **Column order still matters.** Skip scan softens the penalty for a missing leading condition when that column has few values; it does not make column order irrelevant. - **Do not drop the price index on faith.** Compare the real query on 18 with and without it, looking at `Index Searches` and buffers, before removing an index that the 17-era design relied on. - **Expect plan changes on upgrade.** Queries that used a sequential scan on 17 may switch to skip scans on 18. That is usually a win, but verify hot queries. - **Mixed fleets.** A replica or staging server still on 17 will not skip, so an index set tuned for 18 can behave differently there. In an interview, the strongest answer names both halves: the mechanism (a generated equality on the skipped column and one index search per value) and the condition (few distinct values in that column, judged from planner statistics), then shows how you would prove it on a real plan with `Index Searches` and buffer counts rather than by assumption.

  • With skip scan in 18, can you drop the separate index on books(price)?
    Only if measurements say so. Skip scan stays efficient while `category_id` has few distinct values; if categories grow into the thousands, or the price query is hot, a dedicated `price` index still reads fewer pages. Compare `EXPLAIN ANALYZE` buffers and `Index Searches` for the real query on 18, and check whether other queries use the index, before dropping it.
  • Why might pg_stat_all_indexes.idx_scan jump after upgrading to PostgreSQL 18?
    `idx_scan` counts index searches, not executions of the scan node. A skip scan that repositions thirty times adds thirty for one execution of the query, and multi-value `IN` lists add one per descent. A rising counter after the upgrade can mean more repositioning rather than more queries, so compare it with the query's call count before concluding anything.

A phone book sorted by city, then surname: to find every Novak you open each city's section at N, read the few Novaks and jump to the next city. With five cities that is five quick lookups; with ten thousand towns you might as well read the whole book.

  • In PostgreSQL 18, column order in a composite index no longer matters.
  • Skip scan works best when the leading column has many distinct values.
  • Before 18, a composite index could never be used without a condition on its first column.
  • Skip scan also applies to multicolumn GIN and BRIN indexes.
  • Index Searches in EXPLAIN ANALYZE counts the rows returned by the index.

Assumes PostgreSQL 18, which added B-tree skip scan and the Index Searches line in EXPLAIN ANALYZE; 17 and earlier have neither.