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.