B-tree
medium 26 minA 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
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 1 | Leaf 2 | Leaf 3 | Leaf 4 | |
|---|---|---|---|---|
| Inserts | 0 | 0 | 0 | 8 |
| Dirty pages | dirty |
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
criticalThe index is sorted by its first column. A query on the second alone must read everything.
Wrongindex = ("created_at", "customer_id")# query: customer_id = 7, newest firstRightindex = ("customer_id", "created_at")# one descent, then neighboursSplitting without passing the key up
majorThe new page has no pointer, so its keys can never be found.
Wrongleft, right = halves(node)# parent unchangedRightleft, middle, right = halves(node)parent.add(middle, right)Random identifiers for a clustered table
majorEach insert touches another page and splits leave them partly empty.
Wrongid = random_uuid()Rightid = time_ordered_id()A function around the indexed column
minorThe index is sorted by the column, not by the result of the function.
Wrongwhere lower(email) = 'a@example.com'Rightcreate 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.