Work backwards
The same two columns, 16 times faster in the other order
An index on (placed_at, status) answered a query in 4.24 ms; the same two columns as (status, placed_at) answered it in 0.27 ms.
The result
Volume 4's indexing lab asked for the first 20 orders since March 2025 with the rare status DISPUTED (300 such orders),
in date order. With an index on (placed_at, status) the query took 4.24 ms and read 960 buffers. With an index on
(status, placed_at) it took 0.27 ms and read 23. With only an index on placed_at, 17.78 ms and 5,881 buffers
(the lab).
Both composite indexes contain exactly the same columns.
Work back from it
First question: in what order does a B-tree index keep its entries?
Sorted by the first column, then by the second within equal first values, like a phone book sorted by surname, then first name (B-trees and B+trees).
Step 1: with `(placed_at, status)`, where are the disputed orders since March?
Scattered: every date since March appears in order, and on each date the few disputed orders sit among all the others. The scan has to walk through every entry since March and check each one's status to find 20 matches.
Step 2: with `(status, placed_at)`?
All the DISPUTED entries are together, and within them already sorted by date. The scan jumps to the first disputed
order on or after 1 March and reads the next 20 entries: exactly what the query wants, in the order it wants.
Step 3: why did the index on `placed_at` alone do worst?
It gives date order but knows nothing about status, so each candidate row must be fetched from the table to check it: far more pages read (5,881 buffers).
The root cause
A composite index is sorted by its leading column first. Put the columns you test for equality first and the range or sort column after, so the matching entries are contiguous and already in order.
What follows from it
- A composite index also serves queries on its leading columns alone, but not on its trailing ones (PostgreSQL 18's skip scan softens this when the leading column has few distinct values).
- Read
EXPLAIN (ANALYZE, BUFFERS): buffers read tell you how much of the index a plan walked.
Recall
In which order should a composite index list an equality column and a range column?
Equality first, then the range or sort column.
Why does `(placed_at, status)` read so much more than `(status, placed_at)` here?
The disputed orders are scattered among all dates since March, so the scan walks them all; with status first they're contiguous and sorted by date.