Key takeaways
- ✓An index is a second copy of some columns, kept sorted, with a pointer to each row. With no index, a customer's latest 20 orders meant reading all 114,629 pages of the table: 106 ms. The right index read 6 pages in 0.012 ms.
- ✓Build the index for the query: the columns it matches exactly first, then the one it sorts by or asks a range of. By customer alone: 105 pages, 0.13 ms (Postgres still had to read and sort all of the customer's orders). By customer, then date: 23 pages, 0.036 ms.
- ✓Put what the query returns in the index too (INCLUDE) and Postgres can answer from the index alone: a covering index. The latest 20 orders went from 23 pages to 6, a year's spend from 50 pages to 6.
- ✓Column order decides which queries an index serves. For cancelled orders in one day, status then date read 7 pages; date then status read 57, because it looks at every order from that day. Indexes that start with the customer didn't help at all.
- ✓An index can make a query slower. With only a date index, Postgres walked it from the newest order, checking each one, until it found 20 of this customer's: 80,546 pages and 169 ms, against 106 ms for reading the whole table. Check the plan with EXPLAIN ANALYZE instead of assuming.
- ✓Every insert updates every index. One at a time, they cost 17% to 63% of inserts a second: least for the index that starts with the date (new rows go at the end), most for the large ones that start with the customer (each new entry lands on a random page).
- ✓An index is cheap while it fits in memory. The three useful indexes together made inserts 13.9× slower (320,022 to 22,964 a second), far worse than their single costs added up (about 86,000). Each batch of 20,000 inserts had to fetch 14,087 pages that weren't in Postgres's 1 GB cache, against none without them.
An index is the most common fix for a slow query, and it usually works. This chapter measures how much it buys, how picking the wrong columns or the wrong column order throws most of that away, how an index can even make a query slower, and what every index costs the writes. The short version: the right index made one query about 8,800 times faster, a different one made it slower, and three useful ones together made inserts 13.9 times slower.
The examples come from Lab 04 (Storage Engines and Indexes) of the system design labs, script 03_indexes.py, which runs four real queries against a 10-million-row table with one index at a time, then keeps three of them together and measures inserts. The same lab's durability tests (the first three exercises of 01_kvstore.py, a small key-value store killed mid-write, and 04_durability.py, Postgres's commit flush) are Chapter 7. The lab's comparison of storage engines (01_kvstore.py Exercise 4 and 02_engines.py) and its connection-pooling script (05_pooling_n1.py) aren't covered in this series. The setup is the same laptop as before (an Apple M4 Max, Docker Desktop with 16 virtual CPUs and 8 GB), running Postgres 18.6 in Docker. Other work kept the laptop busy (a load average of about 8), so read the shapes, not the last digit.
The table, and what a page is
The table is orders: 10 million orders from 100,000 customers, about a hundred each. Each order has an id, a customer_id, a status (70% shipped, 15% paid, 10% new, 5% cancelled), a created_at time, a total_cents and a short note. The lab's setup script (00_setup.py) creates the same rows on every machine: orders are written in id order, one every 6.3 seconds of simulated time from January 2024, so the table covers about two years and sits on disk in date order. Each order's customer is effectively random, so one customer's orders are scattered all over the table.
Postgres stores a table in pages of 8 KB. This one has 114,629 pages (about 0.94 GB; the lab gives about 1.1 GB with its primary key). A page is the unit Postgres reads: to look at one row, it reads the whole page that holds it. So the cost of a query is roughly the number of pages it touches.
Think of a filing room. Each page is a drawer of order slips, kept in the order they arrived. That's no help for finding one customer's orders. An index is a card file sorted by something useful: each card holds a few columns of one row and points to the drawer that holds the rest. The card files are kept in drawers too, so reading an index also costs pages. In Postgres the usual index is a B-tree: a sorted structure a few levels deep, so finding the first matching card takes a handful of page reads, and the cards after it come in sorted order.
How the lab measures
For each index, the lab builds it, runs each query with EXPLAIN (ANALYZE, BUFFERS), and drops it again. EXPLAIN ANALYZE runs a query and reports what Postgres really did: which plan it chose (the steps it used to find the rows), how long it took, and, with BUFFERS, how many pages it touched. A query on a cold system would also wait for the disk; here every query ran once first, so the pages were already in memory and the times are for a warm cache. Each figure is the median of 30 runs with a random customer or day each time (3 runs for the slow full scans).
The plans you'll see:
| Plan | What Postgres does |
|---|---|
| Seq Scan | Reads the whole table, page by page ("sequential scan") |
| Bitmap Heap Scan | Collects the matching rows' locations from the index, then reads those table pages in page order |
| Index Scan | Walks the index in its order and fetches each matching row from the table |
| Index Only Scan | Answers from the index alone, without visiting the table |
The four queries (the lab calls them Q1 to Q4):
| Query | SQL (shortened) |
|---|---|
| A customer's latest 20 orders, like an order history page | WHERE customer_id = ? ORDER BY created_at DESC LIMIT 20 |
| A customer's new orders | WHERE customer_id = ? AND status = 'new' |
| Cancelled orders in one day | WHERE status = 'cancelled' AND created_at within one day |
| A customer's spend in one year | SELECT sum(total_cents) WHERE customer_id = ? AND created_at within 2024 |
One customer's latest 20 orders
The first query returns the date and total of one customer's 20 newest orders.
| Index | Plan | Pages touched | Median time | vs. no index |
|---|---|---|---|---|
| none (only the primary key, on id) | Seq Scan | 114,629 | 106 ms | |
(customer_id) |
Bitmap Heap Scan | 105 | 0.13 ms | 816× faster |
(customer_id, created_at) |
Index Scan | 23 | 0.036 ms | 2,946× faster |
(customer_id, created_at) INCLUDE (total_cents) |
Index Only Scan | 6 | 0.012 ms | 8,838× faster |
- No index. Postgres has one option: open every drawer, all 114,629 pages, to find this customer's hundred or so orders. That's 106 ms, about a tenth of a second, for one visit to an order history page.
- By customer. Find this customer's cards and open the drawer each one points to. The orders are scattered, so that's about a hundred drawers, plus a few pages of cards: 105 pages. This card file doesn't promise date order, so Postgres reads all of the customer's orders, sorts them and keeps 20.
- By customer, then date. An index on two columns, a composite index, is sorted by the first column, then by the second within each value of the first. This customer's cards now sit together in date order, so Postgres reads the newest 20 and stops: about 20 drawers plus a few pages of cards, 23 pages.
- Plus the total on the card.
INCLUDE (total_cents)stores the total in each card without sorting by it. Now the cards hold everything the query returns, the date and the total, so Postgres can skip the drawers: 6 pages, 0.012 ms. An index that holds every column a query needs is a covering index, and the plan that uses it is an Index Only Scan.
The orders table: 10 million orders in 114,629 pages (drawers) of 8 KB, kept in the order they arrived. An index is a card file sorted by something useful; each card points to a drawer.
none (primary key only)
Postgres has one option: open every drawer, all 114,629 pages, to find this customer's hundred or so orders.
To scale: the grey area is the table, one unit per page. Page counts and times are measured (Postgres's EXPLAIN ANALYZE, warm cache, median). Where the lit pages sit is an illustration; counts under a thousand are drawn as larger marks so they show up. The table really is in date order, which is why the date walk is drawn from the newest end. Page counts include the index's own pages (the card files live in drawers too).
The covering index helped the year's-spend query the same way: 50 pages with (customer_id, created_at), 6 with the total included (0.074 ms to 0.029 ms). "Skip the drawers" is nearly but not quite always true: an Index Only Scan still visits a table page if rows on it changed since the table was last cleaned up (VACUUM), because only the table knows whether a changed row is visible yet.
Column order
Same two columns, a different question: how many orders were cancelled on one day? It matches status exactly and asks for a range of created_at.
| Index | Plan | Pages touched | Median time |
|---|---|---|---|
| none | Seq Scan | 114,553 | 127 ms |
(status, created_at) |
Index Only Scan | 7 | 0.076 ms |
(created_at, status) |
Index Only Scan | 57 | 0.31 ms |
any index starting with customer_id |
Seq Scan | 112,699–114,553 | 117–179 ms |
Status first, then date: all of that day's cancelled cards sit together, so Postgres reads exactly those. Date first, then status: that day's cards sit together, but cancelled ones are mixed in with the other 95%, so Postgres reads every card from the day and skips the ones that weren't cancelled. 8× the pages for the same two columns.
It's like a phone book. Sorted by last name, then first name, it finds "Smith, John" quickly, and all the Smiths. It can't find everyone named John. And an index that starts with customer_id is no help here at all: Postgres reads the whole table, about as slowly as with no index. (The 117–179 ms spread among those full scans is noise on a busy laptop, not the indexes.)
The rule, from the lab: the columns the query matches exactly first, then the one it sorts by or asks a range of. After a range, the entries are no longer grouped by the next column, so columns after it can only be checked, not jumped to.
Try every query against every index:
SELECT count(*) FROM orders WHERE status = 'cancelled' AND created_at >= $1 AND created_at < $1 + interval '1 day'
Index (one at a time) · pages touched, log scale · median time
(status, created_at): Index Only Scan, which means answer from the index alone, without visiting the table.
Match status exactly, a range on created_at. Status first, then date: that day's cancelled cards sit together, 7 pages. Date first, then status: every card from that day, skipping the ones that aren't cancelled, 57 pages. Indexes that start with customer_id can't help.
Each index was built alone, measured, and dropped. Times are medians of 30 runs (3 for the slow full scans) with a random customer or day each run. Full scans took 102 to 179 ms across these queries and runs: that spread is noise on a busy laptop, not the index, so a Seq Scan row counts as "no help".
The new-orders query shows the rule from another side: (customer_id, status) matches both columns and read 11 pages in 0.025 ms. Indexes that only start with customer_id narrowed it to the customer, then checked each of their orders: 97 to 114 pages. The covering index took 0.77 ms there, slower than plain (customer_id) at 0.12 ms: it's a bigger index, and the extra columns don't help that query.
The index that made it slower
Back to a customer's latest 20 orders, but this time the only index is (created_at, status). Faster or slower than no index?
| Index | Plan | Pages touched | Median time |
|---|---|---|---|
| none | Seq Scan | 114,629 | 106 ms |
(created_at, status) |
Index Scan | 80,546 | 169 ms |
Slower. Postgres chose to walk the date index backwards from the newest card, fetching each order to check whose it was, until it found 20 of this customer's. With a hundred-odd orders spread over two years, that meant 80,546 pages, card by card. One quick pass through every drawer, reading pages in order, was faster.
The index gives the right order, newest first, but doesn't narrow anything down by customer. Postgres's planner, the part that picks a plan, chose this one anyway. (Why isn't recorded: the lab saved the plan's type, time and pages, not the estimates behind the choice.) So don't assume an index helps. Look at the plan with EXPLAIN ANALYZE: which plan ran, how long it took and how many pages it touched.
What an index costs
Indexes aren't free. An insert adds one row, and every new row needs a new card in every card file. The lab measured inserts a second with each index on its own: 20,000 single-row inserts in one transaction (so no commit is paid per row; Chapter 7 is about what a commit costs), the median of 3 batches, deleted again afterwards.
| Index | Size | Build time | Inserts a second | vs. no index |
|---|---|---|---|---|
| none | 326,305 | |||
(customer_id) |
71 MB | 1.4 s | 213,715 | −35% |
(customer_id, created_at) |
315 MB | 1.9 s | 146,408 | −55% |
(customer_id, created_at) INCLUDE (total_cents) |
406 MB | 2.1 s | 119,620 | −63% |
(customer_id, status) |
79 MB | 2.2 s | 194,220 | −40% |
(status, created_at) |
320 MB | 3.7 s | 234,498 | −28% |
(created_at, status) |
319 MB | 1.3 s | 271,785 | −17% |
New orders are the newest, so their cards in a date-first file go at the end, on the same few pages. Cards in a customer-first file go somewhere in the middle, on a different page each time. Bigger cards, with the date and the total, cost more. ((customer_id) is 4.4× smaller than (customer_id, created_at) because Postgres stores a repeated key once with a list of rows, and each customer appears about a hundred times.)
Three together
Then the lab kept three useful indexes together: the two winners so far, the covering index and (status, created_at), plus (customer_id, status) for the new-orders query. This second test measured its own baseline, so the numbers differ a little from the table above.
| Inserts a second | Index storage | Pages fetched from outside the cache, per 20,000 inserts | |
|---|---|---|---|
| Primary key only | 320,022 | 0 | |
| With all three | 22,964 | 805 MB | 14,087 |
13.9× slower. Their single costs were 63%, 40% and 28%. Adding up the extra time each one cost per insert predicts about 86,000 inserts a second, not 23,000. Something else happened.
Postgres copies the pages it uses into a cache in memory, shared_buffers: a desk where it keeps the drawers it's working with. Here the desk holds 1 GB, and the table alone (about 1.1 GB) already fills it. New orders only touch the end of the table, so without the indexes that was fine: 0 pages fetched. But each new card in a customer-ordered index goes on a random page, and that page is usually not on the desk. With the three indexes, every 20,000 inserts had to fetch 14,087 pages first.
starts with a random column: each insert lands on a different page
random column first, bigger cards
random column first, the biggest cards
random column first
starts with the insertion time: new cards go at the end
Every insert adds a card to every card file. Files sorted by customer cost the most: each new card goes somewhere in the middle, on a different page each time, and bigger cards cost more. The file that starts with the date costs least: new orders are the newest, so their cards go at the end.
An index is cheap while it fits in memory. Once table and indexes outgrow it, every insert into an index that puts new entries on random pages may first have to fetch a page. The lab's ways out: fewer or smaller indexes (drop unused ones, or index only the rows a query needs, a partial index), more memory, or partitioning: splitting the table into smaller tables, by month for example, so the part being written and its indexes stay small.
Caveats
- One run, one busy laptop. The load average was about 8 at the end of this run. The full scans of the same table took 102–179 ms across queries and indexes, so differences of that size between full scans are noise. The big ratios (100× and more) are not.
- Warm cache. Every query ran once before it was timed, so its pages were in memory. On a cold system, or a table much bigger than memory, the page counts matter even more, because each page may be a disk read.
- One customer isn't every customer. Each run picked a random customer or day; the figures are medians. A customer with 300 orders would touch more pages with
(customer_id). - The page counts are Postgres's own buffer counts for the whole plan, index pages included. The 14,087 are pages that weren't in Postgres's cache; the operating system may still have had some of them in its own memory, so they aren't necessarily disk reads.
- Inserts ran in one transaction. That isolates the cost of maintaining the indexes. Real inserts each commit, and a commit has its own cost, the subject of Chapter 7.
- Why the planner picked the slower plan isn't recorded. The lab saved the plan type, time and pages, not the planner's estimates.
The checklist
- Write down the query before the index: which columns it matches exactly, which it sorts by or asks a range of, which it returns.
- Exact-match columns first, then the sort or range column. An index on (a, b) serves
a = ?anda = ? AND b > ?, but notb = ?. - Consider covering it. If the query returns only a few more columns,
INCLUDEthem so Postgres can answer from the index alone. It makes the index bigger. - Check the plan with
EXPLAIN (ANALYZE, BUFFERS): the plan type, the time and the pages touched, before and after. An index can make a query slower. - Measure what it costs writes, at the table's real insert rate. Indexes that start with a random column cost the most.
- Check that table plus indexes fit in memory. Past that, index costs stop adding up and start multiplying.
- Drop indexes nothing uses. Every one is paid for on every insert.
Practice: pick the index
Write the lab's arithmetic and the rules behind it: how many times faster an index made a query, the table's size from its pages, what an index cost inserts, what single costs predict when indexes are kept together, how many of an index's columns narrow a query, whether an index hands rows back in the right order, and whether it covers the query. The tests use the recorded run: 816×, 2,946× and 8,838× faster, 1.6× slower for the date index, −35% to −63% for inserts, about 86,000 a second predicted against 22,964 measured.
Quiz
1.A query asks for one customer's orders, newest first, 20 of them. Which index serves it best?
2.The same index gets INCLUDE (total_cents), and the query returns created_at and total_cents. What changes?
3.For 'cancelled orders on one day', which index reads fewer pages?
4.The only index on the orders table is (created_at, status). How did a customer's latest 20 orders compare with no index at all?
5.Which single index cost inserts the least, and why?
6.Three indexes that each cost 28–63% of inserts alone made inserts 13.9× slower together. What explains it?
Check your understanding
Try each question before opening its answer.
Why did the index on customer alone read 105 pages for a customer's latest 20 orders, and the one on customer, then date, only 23?
The customer index finds all of the customer's orders but doesn't keep them in date order, so Postgres fetched all of them (about a hundred, each on a different page), sorted them and kept 20. With date as the second column, the customer's entries are already sorted by date, so Postgres read the newest 20 and stopped: about 20 table pages plus a few index pages.
What is a covering index, and what did it buy here?
An index that holds every column a query needs, here by adding total_cents with INCLUDE. Postgres can then answer from the index alone (an Index Only Scan) without reading the table: a customer's latest 20 went from 23 pages to 6 (0.036 to 0.012 ms), and a year's spend from 50 pages to 6. The price was size (406 MB against 315) and insert cost (−63% against −55%).
Status then date read 7 pages for one day's cancelled orders; date then status read 57. Why, if they hold the same columns?
An index is sorted by its first column, then the second within it. Status first puts one day's cancelled orders side by side. Date first groups the whole day, with cancelled orders mixed among the other 95%, so Postgres reads every entry from that day and skips most. Exact-match columns go first, then the range.
How can adding an index make a query slower than no index at all?
The planner may pick a plan that uses it badly. With only a date index, Postgres walked it from the newest order, fetching each one to check the customer, until it found 20: 80,546 pages and 169 ms, against 106 ms for one sequential pass over the whole table. EXPLAIN ANALYZE shows the plan that ran, its time and the pages it touched.
Why did the index starting with the date cost inserts 17%, and the one on customer alone 35%, though it's under a quarter of the size?
Where a new entry goes matters more than size. New orders are the newest, so in a date-first index their entries go at the end, on the same few pages. In a customer-first index each new entry lands on a different page somewhere in the middle.
Three indexes that cost 63%, 40% and 28% alone made inserts 13.9× slower together. What would you check, and what would you do?
Whether table plus indexes fit in Postgres's cache (shared_buffers). Here the table (about 1.1 GB) already filled the 1 GB cache and the indexes added 805 MB, so inserts into the customer-ordered indexes had to fetch a page first: 14,087 per 20,000 inserts, against none without them. Adding up the single costs predicted about 86,000 inserts a second; measured, 22,964. Options: fewer or smaller indexes (drop unused ones, or partial indexes), more memory, or partitioning the table so the part being written stays small.
Someone proposes an index for a slow query. What do you ask before adding it?
Which plan it enables and what it really does, measured with EXPLAIN ANALYZE before and after; how many writes a second the table takes and what the index costs each one; and whether the table and all its indexes still fit in memory.
Next up: Chapter 7, durability: what survives a crash. Every insert here ran inside one transaction. The next chapter commits them one by one and asks: when the database says a write is saved, is it really?