A PostgreSQL index lab on an airline dataset: B-tree, hash, LIKE, composite and covering indexes
Hands-on EXPLAIN ANALYZE on PostgreSQL 18 and 2 million bookings: with and without an index, B-tree vs hash, LIKE with collations and pg_trgm, when the planner skips an index, composite column order and skip scan, ORDER BY, covering indexes with INCLUDE, and how to review indexes an AI proposes.
On this page
1. The problem
The "bookings today, price from 4 million" screen reads 1,370 index pages even though both columns are indexed. Swap the two columns and the same query reads 33 pages. Having an index doesn't mean having the right one.
2. Key idea
A B-tree is a list sorted by its composite key. It is fast only when the query narrows it to a small contiguous slice. Think of a phone book sorted by surname then first name: "Nguyen An" jumps to one page; "surnames A to M, first name An" means flipping through half the book.
Equality columns jump to a point; a range column reads a contiguous slice; columns after the range can only filter entry by entry. So the kind of condition decides column order, not cardinality.
| Tool | Use when | Don't use when |
|---|---|---|
| Single-column B-tree | equality, range, ORDER BY ... LIMIT on a small share |
fetching most of the table |
Composite (equality, range) |
several conditions together, one hot query | ordering columns by cardinality |
INCLUDE (covering) |
skip heap reads for a hot query | columns that change often (lose HOT updates) |
| Hash | equality only, long keys, measured | range, sort, unique |
pg_trgm + GIN |
LIKE '%abc', substring search |
you need relevance scoring |
| BRIN | time columns written in order | scattered data, single-row lookups |
An index without a query that needs it is waste: it only adds one more write to every INSERT.
3. In PostgreSQL
Step 5, the one worth remembering. Run it on a copy so the real table is untouched.
CREATE TABLE bookings0 AS TABLE bookings; -- no indexes or constraints copied
CREATE INDEX b_date_amount ON bookings0 (book_date, total_amount);
VACUUM ANALYZE bookings0;
EXPLAIN ANALYZE SELECT * FROM bookings0
WHERE total_amount >= 400000 -- range, keeps 16% of the table
AND book_date >= '2017-03-01' AND book_date < '2017-03-02';
-- Bitmap Index Scan on b_date_amount: the index node reads 33 pages
DROP INDEX b_date_amount;
CREATE INDEX b_amount_date ON bookings0 (total_amount, book_date);
-- same query: the index node reads 1,370 pages (range first, the next column only filters)PostgreSQL 17 and earlier: write EXPLAIN (ANALYZE, BUFFERS). MySQL InnoDB follows the same column-order rule, has skip scan since 8.0.13, and has no bitmap scan.
The seven lab steps and their results
Each step compares an unindexed copy with an indexed one on an airline dataset (tickets, 3.1 million rows). Guess first, then run.
| Step | Question | Result |
|---|---|---|
| 1 | Look up one ticket with and without a B-tree | ~29,000 pages vs 4 |
| 2 | Hash or B-tree | =: 3 pages vs 4; >=: hash can't help |
| 3 | LIKE 'abc%', LIKE '%abc' |
non-C collation needs text_pattern_ops; suffixes need pg_trgm |
| 4 | 1 day, 1 month, 1 year | 94% of the table: Seq Scan is right, forcing the index is 9× slower |
| 5 | Composite column order | 33 pages vs 1,370 |
| 6 | ORDER BY with a range |
a range on the first column still needs a Sort |
| 7 | Covering index with INCLUDE |
Index Only Scan, 4 pages |
PostgreSQL 18 skip scan: when it helps, when it hurts
Without a condition on the first column, PostgreSQL 18 can still use a B-tree by skipping through each value of that column. The Index Searches line in the plan counts how many times it descends from the root.
| Index | Query | Plan |
|---|---|---|
(passenger_name, ticket_no), 8 leading values |
WHERE ticket_no = ? |
Index Searches: 17, 69 pages, 0.05 ms |
(total_amount, book_date), 5,667 leading values |
book_date within one day |
Index Searches: 1958, ~15,000 random page reads; 212–316 ms cold |
Few leading values: skip scan helps. Many leading values: thousands of tree descents, sometimes worse than the old Seq Scan. It does not replace an index in the right order.
4. Working with AI
AI often orders columns "high cardinality first". What you keep: the real query, the before/after plan, the write cost.
Hand to AI: fake data, EXPLAIN ANALYZE scripts per variant, listing indexes with idx_scan = 0.
Check in AI-written code:
- Every new index comes with the query it serves and a before/after plan.
- Column order: equality first, range or sort last.
- Compare
Buffers(especiallyread), not just one run's milliseconds. - Migrations use
CREATE INDEX CONCURRENTLY, outside a transaction. - No duplicate of an existing index:
(a)is redundant next to(a, b).
5. Exercises
Exercise 1: Review an AI-proposed index
The AI explains: "created_at goes first because its cardinality is higher than status (3 values)". Find the bug, show how a plan proves it, fix it.
-- WHERE status = 'PAID' AND created_at >= now() - interval '1 day'
-- ORDER BY created_at DESC LIMIT 50
CREATE INDEX orders_created_status ON orders (created_at, status);Solution to Exercise 1
created_at is a range, so status after it only filters: the index reads every order from the day in all three statuses and throws two thirds away.
Fix: CREATE INDEX CONCURRENTLY orders_status_created ON orders (status, created_at DESC). Equality first, so for one status the index returns rows already in created_at DESC order: the plan is an Index Scan under Limit, no Sort, stopping after a few pages.
Proof: run EXPLAIN ANALYZE with each index on a copy of the table and compare the index node's Buffers and whether a Sort node appears.
Exercise 2: Read an incident after an upgrade
After upgrading PostgreSQL 17 to 18, a 2 a.m. report job slows from ~50 ms to 200–300 ms; rerun immediately, it takes 38 ms. The slow plan: Bitmap Index Scan on bookings1_amount_date, Index Cond only on book_date, Index Searches: 1958, Buffers: shared hit=3904 read=11141. Diagnose it, explain why the second run is fast, say what you do in 15 minutes, and fix the root cause.
Solution to Exercise 2
- Diagnosis: the query doesn't filter on
total_amount, the index's first column. Version 17 couldn't use the index and did a sequential Seq Scan. Version 18 picks skip scan: nearly 2,000 tree descents, ~15,000 random page reads. - Why the rerun is fast: every page is now in
shared_buffers(readdrops to 0). A nightly job always meets a cold cache, so measure thereadpart, not the second run. - 15 minutes: confirm on a replica; if you must fix it now,
SET enable_bitmapscan = offin the job's session, not server-wide. - Root fix: the right index for this query,
(book_date)or(book_date, total_amount), or move the report to a summary table. After the upgrade, re-ANALYZEtables with extended statistics.
Summary
- Measure with
Buffers, not milliseconds. - Default to B-tree; hash only for
=and only after measuring. - Fetching most of the table, Seq Scan is right.
- Composite: equality first, range and sort last.
Index Searchestells you whether skip scan is helping or hurting.
Read more: Part 3: Join algorithms and partitioning.
Practice interview questions on this topic
- Why does a query still do a Seq Scan despite an index, and is a Seq Scan always bad?
- Which queries can a composite index (a, b, c) serve, and how should you order its columns?
- Besides B-tree, what index types does PostgreSQL offer (Hash, GIN, GiST, BRIN), and when?
- How do you decide on and add an index (even unique) to a 200-million-row production table?
- What is a covering index, and how do Index Scan, Index Only Scan and Bitmap Heap Scan differ?
Comments
Community rules