Data Structures & Algorithms / Module 6: Trees

Topic 6.4

B-trees

A very short tree with wide nodes: the structure behind database indexes.

10 min · advanced

Watch: count the disk reads. Wide boxes hold many numbers at once, so the tree is short and needs few reads.

20 405 10 1525 30 3545 50 55
  • being checked
  • passed / marked
  • finished / the result
Step 1 of 3

A B-tree with the same 11 keys. Each node holds several sorted keys and is read from disk in one go.

Reading one node from disk is far slower than comparing keys in memory. Wide nodes make the tree short, so there are fewer reads.
find:

The problem is the disk

Comparing two numbers in memory takes around a nanosecond. Reading from an SSD takes tens to hundreds of microseconds, thousands of times longer. A disk also always reads a whole block at once (usually 4 KB to 16 KB), not a single number. So what you want to save is the number of disk reads, not the number of comparisons.

Wide nodes, short tree

A binary tree stores one key per node, so a million keys stand about 20 levels tall: up to 20 disk reads. A B-tree fills a whole disk block with keys. If one node holds 500 keys, then:

  • 1 level: 500 keys
  • 2 levels: 500 × 500 = 250,000 keys
  • 3 levels: about 125 million keys

Finding one row among 125 million takes just 3 disk reads, and the root is usually already in memory.

Staying balanced by splitting

New keys always go into a bottom node. If that node is full, it splits in two and its middle key moves up to the parent. If the parent is full too, it splits as well, and so on. The tree only grows taller when the root splits, so every leaf is always at the same depth. A B-tree can never turn into a chain like a plain BST.

Code, for programmersThe index you create is a B-tree
-- PostgreSQL and MySQL (InnoDB) build a B-tree (strictly, a B+tree) by default
CREATE INDEX idx_orders_created ON orders (created_at);

-- Uses the index: walk down to the first key, then read along in order
SELECT * FROM orders
WHERE created_at BETWEEN '2026-03-01' AND '2026-03-15';

-- Can't use it well: the function hides the sorted key
SELECT * FROM orders WHERE date_trunc('day', created_at) = '2026-03-01';

Quiz

  1. Why does a B-tree put many keys in one node?

  2. One node holds 100 keys. Roughly how many keys can 3 levels reach?

  3. A query with WHERE created_at BETWEEN … uses a B-tree index well because…

0 of 3 answered.