A B-tree is a self-balancing search tree whose nodes hold many sorted keys and have many children, typically sized to fill one disk page. Because each node branches hundreds of ways, a B-tree over a billion keys is only three or four levels deep, so a lookup costs a handful of disk reads instead of thirty. All leaves sit at the same depth, and the tree grows by splitting nodes upward toward the root. Its variant, the B+ tree, is the index structure inside almost every relational database and many file systems.
Think of it like
Signs in a giant library
In a library with ten million books, the lobby sign says which floor holds which range of call numbers. On that floor, a sign at the stairs says which aisle holds which sub-range, and each aisle sign points to the right shelf. Three signs and you are at the book. Each sign lists many ranges, not just "left or right", which is what keeps the trip so short. A B-tree is that hierarchy of wide signs, and every sign is one disk page.
Why binary trees fail on disk
Storage is read in pages (typically 4 to 16 KB), and reading one byte costs the same as reading the whole page. A random read is slow: roughly 100 microseconds on an SSD and about 10 milliseconds on a spinning disk, versus around 100 nanoseconds for RAM. A balanced binary tree over a billion keys has about 30 levels, and each level is a separate random read. The fix is to make each node as wide as a page so that one read eliminates hundreds of possibilities at once.
Binary tree, n = 10⁹
30 levels
⌈log₂ n⌉ random reads
B-tree, fan-out 100
5 levels
⌈log₁₀₀ n⌉
B-tree, fan-out 1,000
3 levels
⌈log₁₀₀₀ n⌉
One HDD seek
≈ 10 ms
30 seeks ≈ 0.3 s per lookup
Order, minimum degree and properties
Following CLRS, a B-tree has a minimum degree t >= 2. (Knuth instead uses the order m, the maximum number of children, so m = 2t.) A B-tree of minimum degree t satisfies:
- Each node stores its keys in sorted order.
- Every node except the root holds between
t − 1and2t − 1keys; the root holds between 1 and2t − 1(unless the tree is empty). - An internal node with
kkeys has exactlyk + 1children. Childiholds the keys that fall betweenkey[i − 1]andkey[i]. - All leaves are at the same depth. The tree is perfectly height-balanced at all times.
[ 20 | 40 ]
/ | \
[ 5 | 10 | 15 ] [ 25 | 30 ] [ 45 | 50 | 60 ]
keys < 20 go left, 20 < keys < 40 go middle, keys > 40 go rightThe half-full rule bounds the height. The root has at least 2 children, every other internal node at least t, so level d holds at least 2t^(d − 1) nodes, each with at least t − 1 keys.
Search
At each node, find the first key that is >= the target (binary search within the node, or a linear scan for small nodes). If it equals the target, done. Otherwise, if the node is a leaf, the key is absent; if not, descend into the child just left of that key. The number of node visits, and therefore disk reads, is O(log_t n).
Insert with node splits
New keys always go into a leaf. If that leaf is full (2t − 1 keys), it is split: its median key moves up into the parent, and the remaining keys form two nodes of t − 1 keys each. If the parent was also full it splits too, and so on. When the root splits, a new root is created above it. That is the only way a B-tree gets taller, which is why all leaves always stay at the same depth: B-trees grow at the root, not at the leaves.
- 1
Check the root
If the root is full, split it first and make a new root holding its median. The height grows by one.
- 2
Descend
Pick the child that should contain the key.
- 3
Split on the way down
If that child is full, split it now, pulling its median into the current node (which has room, because it was never full on arrival). Choose the correct half to continue into.
- 4
Insert in the leaf
The leaf is guaranteed to have room; insert the key in sorted position.
| Insert | What happens (t = 2, at most 3 keys per node) | Tree afterward |
|---|---|---|
| 10, 20, 30 | Fill the root leaf | [10 20 30] |
| 40 | Root is full: split, median 20 moves up into a new root | [20] over [10] [30 40] |
| 50 | Leaf has room | [20] over [10] [30 40 50] |
| 60 | Child [30 40 50] is full: split, 40 moves up | [20 40] over [10] [30] [50 60] |
| 70 | Leaf has room | [20 40] over [10] [30] [50 60 70] |
Deletion, in overview
Deletion must keep every non-root node at least t − 1 keys. Like insertion, it can be done in one downward pass by fixing nodes before entering them: never descend into a child that has only the minimum number of keys.
| Situation | Fix |
|---|---|
| Key is in a leaf with spare keys | Remove it directly. |
| Key is in an internal node | Replace it with its predecessor (or successor) from a child that has at least t keys and delete that one below; if both neighboring children are minimal, merge them around the key first. |
| About to enter a minimal child; a sibling has spare keys | Borrow (rotate): the parent's separator moves down into the child and the sibling's nearest key moves up to replace it. |
| About to enter a minimal child; siblings are minimal too | Merge the child, the parent's separator key and a sibling into one node of 2t − 1 keys. |
| The root ends up with no keys | Its only child becomes the new root, and the height shrinks by one. |
B+ trees
Databases almost always use the B+ tree variant, which makes two changes: internal nodes hold only separator keys for routing, and all actual records (or row pointers) live in the leaves, which are linked into a list.
[ 30 | 60 ] internal: keys only
/ | \
[10 20] <---> [30 40 50] <---> [60 70 80] leaves: keys + rows, linked
SELECT ... WHERE id BETWEEN 35 AND 75:
descend once to the leaf holding 35, then follow the links right until 75B-tree
- Records stored in every node
- A search can stop early at an internal node
- Range scans must move up and down the tree
- Each key appears exactly once
B+ tree
- Records only in leaves; internal nodes are pure routing
- Smaller internal entries mean higher fan-out and fewer levels
- Linked leaves make range scans sequential reads
- Every lookup costs the same: root to leaf
Why databases use B+ trees
Take MySQL InnoDB's 16 KB pages. An internal entry is a key plus a child page number, say 8 + 6 bytes, so one internal page holds over a thousand entries. A tree with a root, one internal level and a leaf level already addresses about a million leaf pages; with tens to hundreds of rows per leaf, three or four levels cover billions of rows. The root and upper levels are hot and stay cached in memory, so a point lookup often needs just one or two actual disk reads.
Page size (InnoDB)
16 KB
Entries per internal page
≈ 1,000+
8-byte key + page pointer
Levels for 10⁹ rows
3 to 4
Disk reads per lookup
1 to 2
upper levels cached
| System | How it uses B-trees |
|---|---|
| MySQL InnoDB | Each table is a clustered B+ tree on the primary key; secondary indexes are B+ trees that store primary-key values. |
| PostgreSQL | The default index type is a B-tree (a Lehman-Yao B-link tree that supports high concurrency). |
| SQLite | Tables and indexes are B-tree variants stored in one file of fixed-size pages. |
| File systems | NTFS, XFS, Btrfs, APFS and ext4's HTree directory index all use B-tree variants for metadata and directories. |
Complexity
| Operation | Disk reads | CPU time | Notes |
|---|---|---|---|
| Search | O(log_t n) | O(log n) | Binary search inside each node |
| Insert | O(log_t n) | O(t · log_t n) | A split moves up to t keys |
| Delete | O(log_t n) | O(t · log_t n) | Borrow or merge on the way down |
| Range scan of k results (B+ tree) | O(log_t n + k / B) | O(log n + k) | B = records per leaf page |
| Space | O(n / t) pages | O(n) | Every non-root node is at least half full |
t is the minimum degree, usually in the hundreds, so log_t n is 3 to 4 even for billions of keys.
Implementation
CLRS-style insertion that splits full nodes on the way down, so a single pass suffices. Each node keeps a sorted key list and, if internal, one more child than keys.
from bisect import bisect_left, insort
class BTreeNode:
def __init__(self, leaf: bool = True):
self.keys: list[int] = []
self.children: list["BTreeNode"] = []
self.leaf = leaf
class BTree:
def __init__(self, t: int = 2):
if t < 2:
raise ValueError("minimum degree must be at least 2")
self.t = t # nodes hold t - 1 .. 2t - 1 keys
self.root = BTreeNode()
def search(self, key: int) -> bool:
node = self.root
while True:
i = bisect_left(node.keys, key) # first key >= target
if i < len(node.keys) and node.keys[i] == key:
return True
if node.leaf:
return False
node = node.children[i] # between keys[i - 1] and keys[i]
def insert(self, key: int) -> None:
if len(self.root.keys) == 2 * self.t - 1:
new_root = BTreeNode(leaf=False) # full root: split, tree grows taller
new_root.children.append(self.root)
self._split_child(new_root, 0)
self.root = new_root
node = self.root
while not node.leaf:
i = bisect_left(node.keys, key)
if len(node.children[i].keys) == 2 * self.t - 1:
self._split_child(node, i) # split before descending
if key > node.keys[i]:
i += 1 # continue into the right half
node = node.children[i]
insort(node.keys, key) # the leaf is guaranteed to have room
def _split_child(self, parent: BTreeNode, i: int) -> None:
"""Split the full child parent.children[i]; its median moves up."""
t = self.t
full = parent.children[i]
right = BTreeNode(leaf=full.leaf)
median = full.keys[t - 1]
right.keys = full.keys[t:] # upper t - 1 keys
full.keys = full.keys[:t - 1] # lower t - 1 keys
if not full.leaf:
right.children = full.children[t:]
full.children = full.children[:t]
parent.keys.insert(i, median)
parent.children.insert(i + 1, right)
tree = BTree(t=2)
for k in [10, 20, 30, 40, 50, 60, 70]:
tree.insert(k)
print(tree.root.keys, [c.keys for c in tree.root.children])
# [20, 40] [[10], [30], [50, 60, 70]]Key takeaways
- B-trees make nodes as wide as a disk page, so fan-out is in the hundreds and height is only 3 to 4 levels for billions of keys.
- With minimum degree t, every non-root node holds t − 1 to 2t − 1 sorted keys, and all leaves are at the same depth.
- Insertion goes into a leaf; full nodes split and push their median up. The tree grows only when the root splits.
- Deletion keeps nodes at least half full by borrowing from a sibling or merging with one.
- B+ trees store data only in linked leaves, giving higher fan-out and fast range scans, which is why database indexes use them.
Common pitfalls
- Confusing the two conventions: CLRS's minimum degree t (max 2t − 1 keys) versus Knuth's order m (max m children).
- Off-by-one errors in a split: the median is
keys[t − 1], each half keeps t − 1 keys, and only internal nodes split their children (t each). - Forgetting to choose the correct half after a proactive split, which sends the key into the wrong subtree.
- Analyzing B-trees only by CPU comparisons: the point is the number of page reads, O(log_t n), not O(log₂ n) comparisons.
- Assuming a B+ tree search can stop at an internal node; internal keys are only routing copies, and the data is in the leaves.
Interview tips
- Open with the disk argument: page-sized reads, slow random I/O, and fan-out turning 30 levels into 3 or 4.
- Walk through a split on a small example (t = 2) to show why all leaves stay at the same depth.
- Contrast B-trees and B+ trees, and explain how linked leaves make
BETWEENandORDER BYqueries cheap. - Connect to system design: clustered vs secondary indexes, why random UUID primary keys cause page splits, and when LSM trees win.
Real-world applications
- Primary and secondary indexes in MySQL, PostgreSQL, SQLite, Oracle and SQL Server.
- File-system metadata and directories in NTFS, XFS, Btrfs, APFS and ext4.
- Embedded key-value stores such as LMDB and BoltDB (copy-on-write B+ trees).
- Any ordered index on block storage where reads and range scans dominate.
Practice problems
Test yourself
Why do databases prefer B-trees over balanced binary search trees for on-disk indexes?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.