AlgoViz

B-tree

medium 26 min

A B-tree is a sorted, always balanced tree with hundreds of keys in each page-sized node.

See it run

Search, split, merge and scan a small tree. Every box is one page.

Operations

Search

Find 42. Each page rules out all ranges but one.

Step 1 of 4

Root

25 50 7510 2030 4055 6580 9027 2933 3641 42 44

Read 1

42 lies between 25 and 50. Take the second pointer.

Step 1: Root

def search(node, key):    i = position(node.keys, key)      # inside one page    if i < len(node.keys) and node.keys[i] == key:        return node    if node.is_leaf:        return None    return search(node.children[i], key)
Page reads
One per level
Comparisons
O(log n)
Binary tree, a billion keys
30 levels

Count pages, then say which of them are already in memory.

In the real world

The same b-tree doing real jobs. Pick one and step through it.

Eight inserts into an index with four leaves. Which pages become dirty?

Step 1 of 3

Ordered keys

Leaf 1Leaf 2Leaf 3Leaf 4
Inserts0008
Dirty pagesdirty

One page to write

Every key is larger than the last, so all eight go to the last leaf.

Step 1: Ordered keys

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Wrong column order

    critical

    The index is sorted by its first column. A query on the second alone must read everything.

    Wrong
    index = ("created_at", "customer_id")# query: customer_id = 7, newest first
    Right
    index = ("customer_id", "created_at")# one descent, then neighbours
  • Splitting without passing the key up

    major

    The new page has no pointer, so its keys can never be found.

    Wrong
    left, right = halves(node)# parent unchanged
    Right
    left, middle, right = halves(node)parent.add(middle, right)
  • Random identifiers for a clustered table

    major

    Each insert touches another page and splits leave them partly empty.

    Wrong
    id = random_uuid()
    Right
    id = time_ordered_id()
  • A function around the indexed column

    minor

    The index is sorted by the column, not by the result of the function.

    Wrong
    where lower(email) = 'a@example.com'
    Right
    create index on users (lower(email))where lower(email) = 'a@example.com'

Interview tips

  • How to explain it

    • A page-sized node with hundreds of sorted keys.
    • Four levels for a billion rows.
    • Splits go up, so it stays balanced.
  • Memory trick

    • B: Big and Balanced.
    • B+: leaves linked.
    • Middle goes up.
  • Choose it when

    • Reads by key or range dominate.
    • Latency must be steady.
    • Order matters.
  • Look elsewhere when

    • Small scattered writes dominate.
    • Only exact matches in memory.
    • Words inside text.