Learn Labs
Indexing & Query Planning

Index Lab: 2 Million Orders

Column order, selectivity, index-only scans and expression indexes, timed with EXPLAIN ANALYZE

labs/indexes.py loads 2,000,000 orders (100,000 customers; 1% pending, 4% shipped, 95% delivered; two years of dates) into a 178 MB table, then times queries with EXPLAIN (ANALYZE, BUFFERS). Each query runs three times and the fastest run counts, so the numbers are warm-cache. "Pages" is how many 8 KB buffers the query touched.

docker compose -f compose_prod.yaml run --rm labs python indexes.py
one customer’s ordersno index (seq scan)23.3 msindex on customer_id0.01 mslatest 10 orders of a customer(created_at, customer_id)9.4 ms(customer_id, created_at)0.02 mssum(amount) over 1,000 customersbitmap heap scan7.8 ms, 13,456 pagescovering, just after UPDATE5.8 ms, 19,923 heap fetchescovering, after VACUUM1.3 ms, 0 heap fetchesWHERE lower(email) = …index on email197 msindex on lower(email)0.02 ms

The basic win

Finding one customer's orders without an index read the whole table, 22,728 pages, in 23 ms. With an index on customer_id: 27 pages, 0.01 ms. The index is 15 MB, which is the price.

Column order in a composite index

The query: a customer's 10 latest orders from the last year.

SELECT * FROM orders WHERE customer_id = 4242
AND created_at > now() - interval '365 days'
ORDER BY created_at DESC LIMIT 10;

(customer_id) only            Bitmap Heap Scan   0.02 ms      27 pages
(created_at, customer_id)     Index Scan         9.44 ms   3,383 pages
(customer_id, created_at)     Index Scan         0.02 ms      13 pages

(created_at, customer_id) is the trap: it has both columns, the planner uses it, and it's over 400 times slower than the right order. The index is sorted by created_at first, so finding one customer means walking a whole year of entries and checking each one's customer_id. With (customer_id, created_at) the customer's rows are one contiguous run, already in date order, and Postgres reads the last 10. Rule: equality columns first, then the range or sort column.

Note the single-column index did nearly as well. With about 20 orders per customer, sorting them is trivial; the composite index pays off when each key has thousands of rows.

Selectivity, and a surprise

The plan was to show the planner ignoring an index on status when a value matches 95% of the rows. It didn't:

count(*), status = 'pending'   (1%)      Index Only Scan    0.78 ms      21 pages
count(*), status = 'delivered' (95%)     Index Only Scan   37.34 ms   1,630 pages
sum(amount), status = 'pending'   (1%)   Index Scan         5.81 ms  13,399 pages
sum(amount), status = 'delivered' (95%)  Seq Scan          55.78 ms  22,728 pages

count(*) needs nothing from the table, and the table had just been vacuumed, so Postgres answered even the 95% query from the index alone (1,630 index pages instead of 22,728 table pages). The index really is the cheapest way there. Ask for sum(amount), which lives in the table, and the planner behaves as the textbook says: index for 1%, sequential scan for 95%.

Two more details hide in these numbers. The full index on status is only 13 MB for 2 million entries because B-tree deduplication (Postgres 13+) stores each repeated value once with a list of row pointers; that's also why the 1% scan touched just 21 pages. A partial index (WHERE status = 'pending') on created_at was 456 kB and answered the same count in 0.92 ms.

Index-only scans need VACUUM

SELECT sum(amount) FROM orders WHERE customer_id BETWEEN 1000 AND 1999

index (customer_id, created_at)        Bitmap Heap Scan   7.80 ms  13,456 pages
covering index, right after an UPDATE  Index Only Scan    5.83 ms  19,252 pages, heap fetches 19,923
covering index, after VACUUM           Index Only Scan    1.28 ms     161 pages, heap fetches 0

A covering index, (customer_id) INCLUDE (amount), holds everything the query needs. But an index doesn't know whether a row version is visible; the visibility map does, one bit per page meaning "every row here is visible to everyone". Right after the UPDATE touched those rows, their pages weren't all-visible, so the "index-only" scan went to the table 19,923 times and touched more pages than the plain index. After VACUUM set the bits: 0 heap fetches, 161 pages, 6 times faster than the bitmap scan. Index-only scans are only as good as the table's vacuum state.

A function on the column

WHERE lower(email) = 'customer4242@example.com'

index on (email)                 Index Only Scan   196.77 ms   2,271 pages
expression index (lower(email))  Bitmap Heap Scan    0.02 ms      27 pages

The index on email stores Customer4242@Example.com, not its lowercase form, so it can't be searched for lower(email). Postgres scanned the whole index (cheaper than the table) and applied lower() to 2 million values. An index on the expression itself made it nearly 10,000 times faster.

What indexes cost

insert 200,000 rows:  primary key only 0.22 s,  primary key + 5 indexes 1.74 s

Every index is updated on every insert (and on every non-HOT update). Five extra indexes made the bulk insert 8 times slower. Unused indexes are pure cost; pg_stat_user_indexes.idx_scan = 0 finds them.

On this page