Skip to content

Lesson 14 of 29Indexes and query performance

How Indexes Work

See why a query reads the whole table, how a B-tree finds one row in three or four page reads, and what every index costs on writes.

18 min read0/5 questions

The orders page loads in 40 ms on your laptop. Six months after launch it takes four seconds, and the database CPU graph is a flat line at the top. Your schema can be well designed and your queries correct, and this still happens. Nothing in the code changed. The table grew from a few thousand rows to twenty million, and the query that finds one customer's orders now reads all twenty million every time. Adding one index makes it fast again, and adding the wrong five makes every checkout slower. This lesson explains what an index really is on disk, why it makes some queries thousands of times faster and others slower, and what it costs, so you can reason about indexes instead of adding them by trial and error.

The cost of a query is pages read

A database does not read rows one at a time. It stores a table in fixed-size pages (8 kB in Postgres, 4 kB by default in SQLite, 16 kB in MySQL's InnoDB) and always reads or writes whole pages. A page holds as many rows as fit, typically dozens to a few hundred. The useful mental model for performance is simple: the cost of a query is roughly the number of pages it touches, and a page that is not already in memory has to come from disk.

Memory helps a lot. Postgres keeps recently used pages in its shared_buffers cache, and the operating system caches more. But a twenty-million-row table is gigabytes, and a query that touches all of it pushes useful pages out of the cache for everyone else.

Without an index, WHERE user_id = 42 has only one option: read every page of the table and test every row. That is a sequential scan (Seq Scan in Postgres, SCAN in SQLite). Its cost grows linearly with the table. An index is a separate structure, sorted by the indexed column, that lets the database go straight to the matching rows. Run this to see the difference on 200,000 rows:

Pythonindex_timing.py
import timefrom shopdb import connectdb = connect() # 200,000 synthetic events spread over 5,000 users.db.executescript("""CREATE TABLE big_events ( id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, kind TEXT NOT NULL, created_at TEXT NOT NULL);WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 200000)INSERT INTO big_events (user_id, kind, created_at)SELECT (i * 7919) % 5000 + 1, CASE i % 4 WHEN 0 THEN 'login' WHEN 1 THEN 'view_product' WHEN 2 THEN 'add_to_cart' ELSE 'checkout' END, datetime('2025-01-01', '+' || (i / 50) || ' minutes')FROM n;""") query = "SELECT kind, created_at FROM big_events WHERE user_id = ?"pages = lambda: db.execute("PRAGMA page_count").fetchone()[0] def timed(label): start = time.perf_counter() for user in range(1, 51): # 50 lookups, like 50 API requests db.execute(query, (user,)).fetchall() ms = (time.perf_counter() - start) * 1000 plan = db.execute("EXPLAIN QUERY PLAN " + query, (1,)).fetchall()[0][3] print(f"{label:<11} {ms:7.1f} ms for 50 lookups plan: {plan}") timed("no index")before = pages()db.execute("CREATE INDEX big_events_user_id ON big_events (user_id)")timed("with index")print("rows per user:", len(db.execute(query, (1,)).fetchall()))print(f"database grew from {before} to {pages()} pages of 4 kB: the index has its own pages")
Output
Press Run (⌘ Enter) to see what happens.

Each user has 40 events. Without the index, every lookup tests all 200,000 rows to find those 40. With it, the plan changes from SCAN to SEARCH ... USING INDEX (user_id=?) and the time drops by about a hundred times. Here everything is in memory; on a real server with the table on disk, the gap is far larger. Notice the last line too: the index is real data with real pages.

Inside a B-tree

Almost every index you create is a B-tree (strictly a B+tree). It is a tree of pages:

  • Leaf pages hold every indexed key in sorted order, each with a pointer to its row. Each leaf also links to the next leaf, so the database can walk keys in order.
  • Internal pages hold separator keys and pointers to child pages: "keys below 20 are down here, 20 to 39 down there".
  • The root is one internal page at the top, where every search starts.

To find a key, the database reads the root, picks the child whose range contains the key, and repeats until it reaches a leaf. To read a range, it finds the first key, then follows the leaf links until it passes the end.

A small B-tree over keys 1 to 59
root 20 | 40root pageleaf 1..9leaf 10..19inner 10keys below 20leaf 20..29leaf 30..39inner 3020 to 39leaf 40..49leaf 50..59inner 5040 and uproot

Look up 34. Every search starts at the root. 34 is at least 20 and below 40, so follow the middle pointer. That is page read 1.

1/5

The real trick is the fanout. An 8 kB page holds hundreds of small keys, so each level multiplies the reach by a few hundred. With a fanout of 300, three levels cover 27 million keys and four levels cover about 8 billion. The Databases lesson in System Design has a table of depth against row count. The practical result: a lookup on a big table costs 3 to 4 page reads, and the top levels are almost always cached, so in practice it is often one or two reads from disk. A binary search tree, with two children per node, would need about 25 levels for 20 million rows, which is why databases use wide trees.

This simulation builds a B-tree over a million keys with 100 keys per page, then counts page reads for a lookup and a range:

Pythonbtree_sim.py
from bisect import bisect_right FANOUT = 100 # keys per page; real 8 kB pages hold hundredskeys = list(range(0, 2_000_000, 2)) # 1,000,000 sorted even keys # Leaf level: sorted keys cut into pages. Leaves are linked left to right.level = [keys[i:i + FANOUT] for i in range(0, len(keys), FANOUT)]levels = [level]# Each parent page stores the first key of each child page.while len(level) > 1: firsts = [page[0] for page in level] level = [firsts[i:i + FANOUT] for i in range(0, len(firsts), FANOUT)] levels.append(level)levels.reverse() # levels[0] is the rootprint("pages per level, root first:", [len(l) for l in levels]) def lookup(key): page_no, reads = 0, 0 for depth, level in enumerate(levels): page = level[page_no] reads += 1 slot = max(bisect_right(page, key) - 1, 0) if depth == len(levels) - 1: return page[slot] == key, reads, page_no page_no = page_no * FANOUT + slot def range_scan(low, high): found, reads, leaf = lookup(low) out = [] leaves = levels[-1] while leaf < len(leaves): page = leaves[leaf] out += [k for k in page if low <= k <= high] if page[-1] > high: break leaf += 1 # follow the link to the next leaf reads += 1 return len(out), reads print("lookup 1,234,568 ->", "found=%s, pages read=%d" % lookup(1_234_568)[:2])print("lookup 1,234,567 ->", "found=%s, pages read=%d" % lookup(1_234_567)[:2])print("range 500,000..502,000 -> %d keys, pages read=%d" % range_scan(500_000, 502_000))print("a full scan would read", len(levels[-1]), "leaf pages")
Output
Press Run (⌘ Enter) to see what happens.

A hit and a miss both cost three reads: proving a key is absent is as cheap as finding it, which is exactly what a UNIQUE check needs. The range of 1,001 keys cost 13 reads: three to descend, then one per extra leaf.

Real B-trees also stay balanced as you insert. When a leaf is full, it splits into two half-full pages and pushes a new separator into its parent, and occasionally the root splits and the tree grows one level taller. Inserting keys in increasing order (identity ids, timestamps, UUIDv7) always hits the rightmost leaf, which stays in memory. Random keys like UUIDv4 split pages all over the tree, which is why Choosing Column Types warned about them.

What the leaf points at

The leaf entry has to lead to the row. How it does that differs between engines, and it changes what is cheap.

Postgres stores rows in an unordered heap: new rows go wherever there is space. Every index, including the primary key, is a separate B-tree whose leaves hold the key and a TID (page number and slot) of the row in the heap. An index scan therefore reads index pages and then fetches each matching row from the heap. If the matching rows are spread over many heap pages, that is many random reads. For medium-sized result sets, Postgres often switches to a bitmap scan: it collects all the matching TIDs from the index first, sorts them by page, and reads each heap page once in physical order.

MySQL InnoDB uses a clustered index: the table itself is the primary key's B-tree, with full rows in its leaves. Lookups by primary key are one descent. A secondary index stores the primary key value instead of a physical pointer, so a lookup through it is two descents: secondary index, then primary key. Two consequences come up in design reviews. A wide primary key (say a 36-character UUID string) is copied into every secondary index and bloats all of them. And a random primary key makes inserts split pages of the table itself, not just of an index.

SQLite is close to InnoDB. An ordinary table is a B-tree keyed by its hidden integer rowid, and a column declared INTEGER PRIMARY KEY becomes an alias for it. Other indexes store the key plus the rowid. A WITHOUT ROWID table is clustered on its declared primary key instead. Watch the plans:

Pythonwhat_the_plan_uses.py
from shopdb import connect, showdb = connect() db.executescript("""CREATE INDEX customers_city ON customers (city);CREATE TABLE sessions (token TEXT PRIMARY KEY, user_id INTEGER NOT NULL) WITHOUT ROWID;""") for sql in [ "SELECT name FROM customers WHERE id = 3", "SELECT name FROM customers WHERE city = 'London'", "SELECT name FROM customers WHERE email = 'ada@example.com'", "SELECT user_id FROM sessions WHERE token = 'abc'", "SELECT name FROM customers WHERE name = 'Ada Lovelace'",]: detail = db.execute("EXPLAIN QUERY PLAN " + sql).fetchall()[-1][3] print(f"{sql}\n {detail}") show(db, "SELECT type, name, tbl_name FROM sqlite_schema WHERE type = 'index' ORDER BY tbl_name, name")
Output
Press Run (⌘ Enter) to see what happens.

The lookup by id goes straight down the table's own B-tree (USING INTEGER PRIMARY KEY). The city lookup uses the index you created, then fetches the row by rowid. The email lookup uses an index you never wrote: UNIQUE created sqlite_autoindex_customers_1, because the only efficient way to enforce uniqueness is an index. Postgres does the same for every primary key and unique constraint. The name lookup has no index, so it scans.

Why not a hash table?

A hash index answers key = value in about one page read, which sounds better than three or four. But it only answers equality. It cannot do <, BETWEEN, LIKE 'abc%', ORDER BY or prefix matches on multi-column keys, because hashing destroys order. A B-tree does all of those with one structure, its upper levels sit in cache anyway, and it supports uniqueness checks. Postgres does have hash indexes (crash-safe since version 10), and they can be smaller for long keys such as URLs that you only ever compare for equality. They are rarely worth choosing over a B-tree. In-memory engines and key-value stores use hashing heavily, because they never need ranges.

Selectivity: when an index does not help

An index pays off when it lets the database skip most of the table. Selectivity is the fraction of rows a condition matches; a condition that matches few rows is highly selective. Cardinality is the number of distinct values in a column. An email column has high cardinality, so email = ? is very selective. A status column with four values has low cardinality, so status = 'shipped' may match 70% of the table.

For a low-selectivity condition, the index is worse than useless. Each match means an index entry plus a fetch from the table, in index order rather than physical order, so the database may read the same table page many times. Reading the whole table front to back is cheaper. Run both and compare:

Pythonselectivity.py
import timefrom shopdb import connect, showdb = connect() db.executescript("""CREATE TABLE big_orders ( id INTEGER PRIMARY KEY, customer_id INTEGER NOT NULL, status TEXT NOT NULL, total_cents INTEGER NOT NULL);WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 200000)INSERT INTO big_orders (customer_id, status, total_cents)SELECT (i * 37) % 20000 + 1, CASE WHEN i % 1000 = 0 THEN 'disputed' WHEN i % 10 < 7 THEN 'shipped' WHEN i % 10 < 9 THEN 'paid' ELSE 'pending' END, (i * 7) % 50000FROM n;CREATE INDEX big_orders_status ON big_orders (status);""")show(db, """SELECT status, COUNT(*) AS n, ROUND(100.0 * COUNT(*) / 200000, 1) AS pctFROM big_orders GROUP BY status ORDER BY n DESC""") def timed(status, hint): sql = f"SELECT SUM(total_cents) FROM big_orders {hint} WHERE status = ?" best = float("inf") for _ in range(3): # best of 3 runs start = time.perf_counter() db.execute(sql, (status,)).fetchone() best = min(best, (time.perf_counter() - start) * 1000) return best for status in ["disputed", "shipped"]: via_index = timed(status, "INDEXED BY big_orders_status") via_scan = timed(status, "NOT INDEXED") print(f"{status:<9} index: {via_index:6.1f} ms full scan: {via_scan:6.1f} ms")
Output
Press Run (⌘ Enter) to see what happens.

INDEXED BY and NOT INDEXED are SQLite hints that force the choice, used here only to compare. For the rare disputed value, the index wins by a huge margin. For shipped, it is slower than scanning even with every page in memory; on disk, the random reads make it far worse.

You normally do not force anything. The query planner estimates how many rows each condition matches from statistics it keeps about each column (distinct values, the most common values and their frequencies, a histogram), prices each possible plan, and picks the cheapest. That is why Postgres happily ignores your index on status for 'shipped' and uses it for 'disputed', and why stale statistics after a big data load cause bad plans. Why the Database Ignored Your Index goes deep on the planner's reasoning. There is no fixed cut-off: it depends on row width, how well the table's physical order matches the index order, and settings like Postgres's random_page_cost.

What every index costs

Indexes are paid for on every write.

  • Write amplification. An INSERT adds an entry to every index on the table. A DELETE has to remove or mark them. An UPDATE that changes an indexed column updates that index.
  • Storage and memory. Indexes compete with the table for cache. A table with ten indexes may have more index pages than table pages.
  • Maintenance. Page splits, and in Postgres, bloat: dead index entries left behind by updates and deletes until VACUUM cleans them, and pages that stay half empty. A bloated index can be rebuilt online with REINDEX INDEX CONCURRENTLY.

Measure the first cost:

Pythonwrite_cost.py
import timefrom shopdb import connectdb = connect() rows = [(i % 5000, f"user{i}@example.com", f"2025-06-{i % 28 + 1:02d}", i % 997) for i in range(50_000)] def load(extra_indexes): db.executescript(""" DROP TABLE IF EXISTS t; CREATE TABLE t (id INTEGER PRIMARY KEY, user_id INTEGER, email TEXT, day TEXT, score INTEGER); """) for i, column in enumerate(["user_id", "email", "day", "score"][:extra_indexes]): db.execute(f"CREATE INDEX t_{i} ON t ({column})") start = time.perf_counter() db.executemany("INSERT INTO t (user_id, email, day, score) VALUES (?, ?, ?, ?)", rows) db.commit() return (time.perf_counter() - start) * 1000 load(0) # warm-up run, not measuredtimes = [load(n) for n in range(5)]for n, ms in enumerate(times): print(f"{n} secondary indexes: {ms:5.0f} ms for 50,000 inserts ({ms / times[0]:.1f}x)")
Output
Press Run (⌘ Enter) to see what happens.

Each index added roughly the cost of the table insert again. In production that shows up as slower writes, more WAL (the write-ahead log that replicas and backups consume), and longer lock hold times.

Postgres has one important optimisation here. Because of MVCC, an UPDATE writes a new version of the row rather than changing it in place, which would normally mean new entries in every index. A HOT update (heap-only tuple) avoids that: if no indexed column changed and the new version fits on the same heap page, the indexes are not touched at all. Indexing a frequently updated column, such as last_seen_at, turns every one of those updates from HOT into a full index update. That is a real, measurable reason to leave a column unindexed.

The rule seniors follow: index for the queries you actually run, check with EXPLAIN that the index is used, and drop indexes that nothing uses.

Index types in Postgres

B-tree is the default and the right answer most of the time. The others exist for data a sorted tree cannot handle.

TypeGood forExample
B-tree=, <, >, BETWEEN, IN, IS NULL, prefix LIKE, ORDER BYCREATE INDEX ON orders (customer_id)
Hashequality onlylong keys compared only with =
GINvalues that contain many items: jsonb, arrays, full-text tsvector, trigramsCREATE INDEX ON products USING gin (attributes)
GiSTranges, geometry (PostGIS), nearest-neighbour, exclusion constraintsUSING gist (during) for booking overlaps
BRINhuge append-only tables where values follow physical order, like event timeUSING brin (created_at) on a log table
HNSW, IVFFlatvector similarity search, from the pgvector extensionembeddings for semantic search

BRIN is worth knowing because it is tiny. Instead of one entry per row, it stores the minimum and maximum value for each range of table pages (128 pages by default), so an index over a billion-row log table can be a few megabytes. It only works when the column correlates with insert order. GIN gets a fuller treatment in the JSON and full-text search lessons later in the course.

Building indexes on a live database

A plain CREATE INDEX in Postgres blocks writes to the table until it finishes, which on a large table can be many minutes. In production, use:

add_index.sql
CREATE INDEX CONCURRENTLY orders_customer_id_idx ON orders (customer_id);

It takes longer and does two passes over the table, but inserts and updates keep working. Two catches: it cannot run inside a transaction block, so migration tools need a flag to run it outside one (Alembic's autocommit_block(), for example), and if it fails partway it leaves an INVALID index behind that still slows writes. Check for one with \d orders in psql, drop it, and retry. Give indexes descriptive names (orders_customer_id_idx), because you will read them in plans and drop them by name.

Check your understanding

Quick check
A 50-million-row orders table has an index on status. 92% of rows are delivered. The planner uses a sequential scan for WHERE status = 'delivered'. What is happening?
Need a nudge? A hint rules out a wrong answer.
Predict the outputPython

Each page holds 400 keys. How many levels does a B-tree over 50 million keys need? What does this print?

import math
rows = 50_000_000
fanout = 400
print(math.ceil(math.log(rows, fanout)))
Need a nudge? Hints walk you through it.
Put it in order5 steps

Put the steps of a Postgres index scan for WHERE email = 'ada@example.com' in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Match the pairs0/5 matched

Match each query need to the Postgres index type that fits it.

Choose an item, then its match on the other side.
Quick check
A MySQL team uses CHAR(36) UUID strings as the primary key of a large InnoDB table with six secondary indexes. Why does a senior engineer object?
Need a nudge? A hint rules out a wrong answer.
Key terms
page
The fixed-size block a database reads and writes: 8 kB in Postgres, 4 kB by default in SQLite, 16 kB in InnoDB.
sequential scan
Reading every page of a table and testing every row. Shown as Seq Scan in Postgres and SCAN in SQLite.
B-tree
A balanced tree of pages with sorted keys in linked leaves. The default index type, good for equality, ranges and sorting.
fanout
How many child pointers fit in one index page. High fanout keeps the tree only a few levels deep.
clustered index
An index whose leaves hold the table rows themselves, as InnoDB does for the primary key. Postgres tables are unordered heaps instead.
selectivity
The fraction of rows a condition matches. Indexes help highly selective conditions, ones that match few rows.
HOT update
A Postgres update that changes no indexed column and fits on the same page, so no index needs a new entry.