Course contents

04. Database Fundamentals Lesson 4 of 10

B-Tree Indexes

Inside the B+tree: pages, fan-out and height, how lookups and range scans walk it, how inserts split pages, and why random keys hurt write-heavy tables.

15 minIntermediate9 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • A B+tree stores sorted keys in leaf pages, with branch pages and a root above them; all leaves are at the same depth.
  • Fan-out in the hundreds keeps height at 3–4 levels for billions of keys; the top levels stay in memory.
  • Range scans descend once and then follow sibling links between leaves.
  • A full leaf splits in two; splits keep the tree balanced and cost extra writes and half-empty pages.
  • Monotonic keys append at the right edge; random keys spread inserts, splits and cache misses over the whole index.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

A B-tree is a balanced, sorted tree of fixed-size pages, designed for storage where reading a page is expensive and reading a byte within it is cheap. Databases use the B+tree variant: all keys with their row pointers (or rows) live in the leaf pages, kept in sorted order and linked to their neighbours; branch (internal) pages above them hold only separator keys and child pointers, up to one root. It is the default index type in PostgreSQL, MySQL/InnoDB, SQL Server, Oracle and SQLite.

Why it exists

Disks and SSDs read in blocks, and every block read costs far more than comparing keys in memory. A binary search tree with one key per node would need about 27 node visits for 100 million keys, each potentially a separate read. A B-tree packs hundreds of keys into each page, so each read narrows the search by a factor of hundreds instead of two. Bayer and McCreight introduced it in 1970 for exactly this reason; the structure has outlived several generations of storage hardware because the block-oriented cost model still holds, even in memory (cache lines).

How it works

Pages and fan-out. A page is 8 KB in PostgreSQL and 16 KB in InnoDB by default. The number of children a branch page can address is its fan-out, determined by key size: a few hundred for integer keys, fewer for long string keys. Height is about log_fanout(n): with a fan-out of 400, three levels address 64 million keys and four levels about 25 billion.

Lookup. Start at the root, binary-search its separators, follow the child pointer, repeat until a leaf. One page read per level. The root and branch levels are a tiny fraction of the index (well under 1% for large fan-outs) and are almost always cached, so a lookup usually costs one leaf read from storage, plus the table row unless the index covers the query.

Range scan. Descend to the first key ≥ the lower bound, then read leaves left to right through the sibling links until the upper bound. The same mechanism serves ORDER BY with LIMIT, MIN/MAX, and prefix matches such as LIKE 'abc%' (with a suitable collation or operator class). Composite indexes sort by the first column, then the second, so they serve equality on leading columns followed by a range or sort on the next.

Insert. Descend to the leaf where the key belongs; if there is room, insert it in sorted position and log the change to the write-ahead log. If the leaf is full, split it: allocate a new page, move about half of the entries, link the new page into the leaf chain, and insert a separator into the parent. A full parent splits in turn; a root split creates a new root, the only way the tree grows taller. Many engines special-case the rightmost leaf: when keys arrive in increasing order the old page is left nearly full instead of half full.

Deletes and bloat. Deletes leave space in pages; engines merge or recycle pages lazily (PostgreSQL's VACUUM marks space reusable; InnoDB merges pages below a threshold). Indexes that see heavy churn can become larger than their live data and benefit from a rebuild (REINDEX CONCURRENTLY, OPTIMIZE TABLE).

Clustered vs secondary. In InnoDB and SQL Server's clustered indexes the leaves of the primary key index are the table rows, and secondary indexes store the primary key as their pointer. In PostgreSQL every index points into a separate heap by physical row location.

When to use it

  • Almost every general-purpose index: primary keys, foreign keys, filters, sorts.
  • Range queries, ordered reads, pagination, "latest N" queries.
  • Composite filters where the column order matches the queries.
  • Mixed read/write workloads where reads must be fast and predictable.

When not to

  • Pure equality lookups at extreme rates where ordering is never needed: a hash index or an in-memory hash map can be cheaper.
  • Write-dominated workloads with random keys and data far larger than memory (event ingestion, time series at high volume): LSM-tree engines (RocksDB, Cassandra, ScyllaDB) turn random writes into sequential ones.
  • Low-selectivity columns, full-text search, geometric or array containment queries: use specialised index types (GIN, GiST, BRIN, inverted indexes).

Trade-offs

Choice You gain You pay
More indexes Faster reads for more queries Every insert/update/delete maintains every index
Lower fillfactor (free space per page) Fewer splits for in-place growth Larger index, more pages to cache and read
Wide or long keys Covering more queries Lower fan-out, taller trees, bigger index
Sequential / time-ordered keys Cheap appends, compact pages Leaks creation order; a hot rightmost page under very high concurrency
Random keys (UUIDv4) No coordination, no ordering leak Splits and cache misses across the whole index

Alternatives

  • Hash indexes: O(1) equality lookups, no ranges or ordering.
  • LSM trees: buffer writes in memory, flush sorted files, merge in the background; fast writes, reads may check several files (mitigated by Bloom filters).
  • BRIN / zone maps: tiny summaries of block ranges for naturally ordered data such as append-only timestamps.
  • Inverted indexes (GIN, search engines) for text and multi-valued columns.

Failure modes

  • Random-key inserts on large tables: write amplification from splits, half-empty pages, and a working set that no longer fits in memory.
  • Index bloat from heavy updates and deletes, making scans and caching less efficient.
  • Too many indexes on a write-heavy table, each multiplying write cost.
  • Wrong column order in a composite index, so the planner cannot use it for the real query.
  • Rightmost-page contention under extreme concurrent inserts of increasing keys (some engines mitigate with optimisations or hash-partitioned indexes).
  • Long index builds that lock writes unless built online.

In production

Prefer bigint sequences or time-ordered UUIDs (UUIDv7, standardised in RFC 9562; or ULIDs) for primary keys of insert-heavy tables. Keep keys short. Check index usage and size (pg_stat_user_indexes, sys.schema_unused_indexes in MySQL) and drop unused ones. Watch bloat and rebuild online when needed. Build indexes concurrently on live tables. Use EXPLAIN (ANALYZE, BUFFERS) to see how many pages a query touches, not just its time.

Common misconceptions

  • "B-tree lookups are O(log₂ n) like a binary tree." They are O(log n) with a base in the hundreds; in page reads that is 3–4, usually 1 from disk.
  • "A bigger table means slower index lookups." Only when it crosses a height threshold, or when the working set no longer fits in memory.
  • "Key order doesn't matter for inserts." It matters a lot once the index is larger than memory.
  • "B in B-tree stands for binary." It does not; the inventors never settled on a meaning (balanced, broad, Bayer, Boeing are all suggested).

Interview angle

When you add an index in a design, be ready to explain why it is fast: pages, fan-out, height 3–4, top levels cached, range scans over linked leaves. Interviewers like the follow-ups: why indexes slow writes (every index is updated, splits), why UUIDv4 primary keys can hurt and what to use instead, how composite index column order follows the query, and when you would choose a hash index or an LSM-based store.

Model assumptions

The B+tree in this lesson is a scripted illustration: scenery pages with keys 1–99 and two children per branch, and moving packets for lookups, the range scan, the insert and the page split. Real pages hold hundreds of entries. The live traffic is simulated with a cost model: one database with 4 connections, a 1 ms index lookup and an insert cost of about 2 ms with sequential keys and about 11 ms with random UUIDv4 keys (lognormal, cv 0.3); queries waiting more than 300 ms for a connection fail. The insert costs stand for the combined effect of splits and cache misses, which the engine does not model page by page. Numbers are illustrative, not benchmarks.

The lesson as textEvery step of the simulation, written out.
  1. 1. Pages in a sorted, balanced tree

    A B-tree index (strictly a B+tree, the variant databases use) is made of fixed-size pages: 8 KB in PostgreSQL, 16 KB in MySQL’s InnoDB. Leaf pages hold the keys in sorted order, each with a pointer to its row (or the row itself in a clustered index). Branch pages hold separator keys: "keys below 25 are in this child, 25 and up in that one". One root page sits on top.

    Every leaf is at the same depth, so every lookup costs the same number of page reads. Leaves are also linked to their neighbours in key order (the lines between the leaves). This illustration uses keys 1–99 and two entries per branch; real pages hold hundreds.

    Scene: Illustration: a B+tree with one root page, two branch pages and four leaf pages holding keys 1 to 99 in order. Each leaf links to the next. The app sends live queries to the database in the background.

    Key idea: A B+tree keeps keys sorted in leaf pages, with branch pages above them acting as a multi-level table of contents.

  2. 2. A point lookup reads one page per level

    WHERE id = 62. The database reads the root (62 ≥ 50: go right), then Branch B (62 < 75: go left), then leaf 50–74, where it finds 62 and its row pointer. Three page reads for a three-level tree, then the row itself.

    A second lookup, for 7, takes the other path: root, Branch A, leaf 1–24. Same depth, same cost. (Scripted illustration; the live queries in the background are simulated with a 1 ms index lookup.)

    Scene: Illustration: a lookup for key 62 reads the root, Branch B and the leaf for 50 to 74, then returns the row pointer. A lookup for key 7 reads the root, Branch A and the leaf for 1 to 24.

    Key idea: Lookup cost = tree height in page reads, the same for every key.

  3. 3. Fan-out keeps the tree shallow

    How many children a page can point to is its fan-out. An 8 KB page with 8-byte keys plus pointers and overhead holds a few hundred entries; take 400 as an illustrative figure.

    Height grows with the logarithm of the row count to base 400: one level addresses 400 rows, two levels 160,000, three levels 64 million, four levels about 25 billion. Doubling the table adds no level until you cross one of those thresholds.

    And the top is small: for 64 million rows the root and branch levels are about 400 pages (≈ 3 MB) and stay in memory, so a lookup usually costs one disk read, the leaf. The packets show four lookups for keys in four different leaves: always root, branch, leaf.

    Scene: Illustration: four lookups for keys in four different leaves, each reading the root, one branch and one leaf. Annotations give the sizes for a fan-out of 400: one root, 400 branch pages, 160,000 leaves, 64 million keys.

    Key idea: Height ≈ log_fanout(rows); with fan-outs in the hundreds, 3–4 levels cover billions of rows.

  4. 4. A range scan descends once, then walks the leaves

    WHERE id BETWEEN 40 AND 80 (or ORDER BY id LIMIT 50). The database descends once to the leaf holding 40, then follows the sibling links: leaf 25–49, leaf 50–74, leaf 75–99, stopping after 80. It never goes back up the tree.

    That is why B-trees serve ranges, sorting and prefix matches so well, and why the order of columns in a composite index matters: the leaves are sorted by the first column, then the second. A hash index can do none of this. (Scripted illustration.)

    Scene: Illustration: a range query for 40 to 80 descends root, Branch A, leaf 25 to 49, then follows the leaf links to the next two leaves and returns, without going back up the tree.

    Key idea: Sorted, linked leaves turn range queries into one descent plus a sequential walk.

  5. 5. Inserting where there is room

    Inserting key 30 follows the same path as a lookup to the leaf where 30 belongs, leaf 25–49. It has free space, so 30 is written into that page in sorted position and the change is logged (write-ahead log) before it is acknowledged.

    One page changed. Every index on the table gets the same treatment on every insert, which is the write cost of indexes. (Scripted illustration.)

    Scene: Illustration: inserting key 30 descends to the leaf for 25 to 49, which has free space; the key is written there and acknowledged.

    Key idea: An insert is a lookup plus a write to one leaf page, as long as the leaf has room.

  6. 6. A full leaf splits

    Now leaf 25–49 is full and key 31 arrives. The database allocates a new page, moves the upper half of the keys into it (37–49), links it between its neighbours, and adds a separator 37 to Branch A so lookups can find it.

    A split writes three or more pages instead of one, and leaves two half-full pages. If the branch is full too, it splits and pushes a separator into the root; if the root splits, a new root is created and the tree grows one level taller. That is the only way a B-tree gains height, and why all leaves stay at the same depth. (Scripted illustration.)

    Scene: Illustration: the leaf for 25 to 49 is full when 31 arrives. It splits: keys 37 to 49 move to a new leaf linked between its neighbours, and Branch A gets a new separator, 37.

    Key idea: Splits keep the tree balanced, at the cost of extra writes and half-empty pages.

  7. 7. Random keys: splits and cache misses everywhere

    An import writes 450 rows per second into the orders table. While the primary key is a sequence, every new key is the largest so far: all inserts go to the rightmost leaf (the packets hitting Leaf 75–99), which stays in memory. Each insert costs about 2 ms here and the database is about a quarter busy.

    One second in, the key switches to a random UUIDv4. Each insert now lands on a random leaf: pages split all over the index and end up about half full, and the leaves being written no longer fit in memory, so inserts wait for disk reads. In this model an insert now costs about 9 ms: the database saturates, inserts queue and some time out.

    Scene: An import sends 500 queries per second, mostly inserts. With sequential keys every insert goes to the rightmost leaf and the database is lightly loaded. After the switch to random UUIDs, inserts land on random leaves, cost about five times as much, the database saturates and some inserts time out.

    Key idea: Random keys spread inserts over the whole index: more splits, emptier pages, and a working set that no longer fits in memory.

  8. 8. Time-ordered keys

    Keep globally unique ids, but make them time-ordered: UUIDv7 (RFC 9562) or a ULID puts a timestamp in the high bits, so new keys are nearly always larger than existing ones. One second in, the switch is live: inserts go back to the rightmost leaf, splits happen only at the right edge (where databases fill the old page completely instead of half), and the hot pages stay in memory.

    Insert cost drops back to about 2 ms, the queue drains and the timeouts stop.

    Scene: One second in, keys become time-ordered UUIDv7 values. Inserts go to the rightmost leaf again, cost about 2 ms, the backlog drains and nothing fails.

    Key idea: Prefer monotonically increasing keys (sequences, UUIDv7) for B-tree primary keys on insert-heavy tables.

  9. 9. What B-trees are good at

    B-trees give O(log n) point lookups with a tiny constant (3–4 page reads, usually 1 from disk), range scans and ordered reads by walking linked leaves, and in-place updates that keep the structure balanced through splits. That combination is why they are the default index in PostgreSQL, MySQL, SQL Server, Oracle and SQLite.

    The costs: every write updates every index, splits leave pages partly empty (bloat, fillfactor), and random keys hurt. For pure equality lookups a hash index can be cheaper; for very write-heavy workloads LSM trees (RocksDB, Cassandra) turn random writes into sequential ones.

    Scene: The B+tree with its root, two branches and five leaves after the split. The database serves inserts with time-ordered keys and is lightly loaded.

    Key idea: B-trees: balanced, shallow, sorted. Great for reads and ranges; every write pays to keep them that way.