Notes
All notes

B-trees and B+ trees: indexes that live on disk

Problem. Binary search trees are fast in RAM, but a database lives on disk, where reading one node costs a whole block fetch. A tree of height 30 needs 30 disk seeks per lookup. B-trees fix this by making each node as wide as a disk block, so the tree stays shallow and every operation costs a handful of seeks. B+ trees go one step further and are what most databases actually use.

B-tree rules (order m)

Fix a maximum number of children m (in practice, hundreds). Every node obeys:

The examples below use m = 3 (at most 2 keys per node) so the splits fit on the page; real orders are far wider, which is why the height stays tiny: a height-3 order-100 tree already holds about a million keys.

Insertion: split on the way down

Insert like in a BST, but whenever you meet a full node, split it first and push the median key up. Splitting proactively (instead of only at the leaf) keeps the code simple: the parent is guaranteed to have room.

Insert 10, then 20: the root just grows.

Insert 5: the root [5, 10, 20] overflows, so the median 10 moves up and we get a new root with two children.

\begin{tikzpicture}[
  n/.style={draw,thick,minimum height=0.7cm,font=\small\ttfamily},
  a/.style={->,thick}
]
  \node[n] (r) at (0,0) {10};
  \node[n] (l) at (-1.7,-1.7) {5};
  \node[n] (rr) at (1.7,-1.7) {20};
  \draw[a] (r.south west) -- (l.north);
  \draw[a] (r.south east) -- (rr.north);
\end{tikzpicture}

Insert 6 (into [5]) and 12 (into [20]). Neither child is full, so both just grow:

\begin{tikzpicture}[
  n/.style={draw,thick,minimum height=0.7cm,font=\small\ttfamily},
  a/.style={->,thick}
]
  \node[n] (r) at (0,0) {10};
  \node[n] (l) at (-1.9,-1.7) {5, 6};
  \node[n] (rr) at (1.9,-1.7) {12, 20};
  \draw[a] (r.south west) -- (l.north);
  \draw[a] (r.south east) -- (rr.north);
\end{tikzpicture}

Insert 30: the right child [12, 20, 30] overflows, so its median 20 moves up into the root. Final tree:

\begin{tikzpicture}[
  n/.style={draw,thick,minimum height=0.7cm,font=\small\ttfamily},
  a/.style={->,thick}
]
  \node[n] (r) at (0,0) {10, 20};
  \node[n] (c1) at (-3,-1.8) {5, 6};
  \node[n] (c2) at (0,-1.8) {12};
  \node[n] (c3) at (3,-1.8) {30};
  \draw[a] (r.south west) -- (c1.north);
  \draw[a] (r.south) -- (c2.north);
  \draw[a] (r.south east) -- (c3.north);
\end{tikzpicture}

Splits can cascade all the way up; if the root itself splits, the tree grows by exactly one level — which is why B-trees stay balanced without rotations.

Search and delete in one paragraph

Search is BST search with a linear scan inside each wide node. Delete removes the key, then fixes an underfull node by borrowing a key from a sibling through the parent, or — if both siblings are minimal — merging two children and pulling a key down. Merge is the mirror image of split, and like split it can cascade to the root (which may then shrink away).

B+ trees: data lives in the leaves

Databases overwhelmingly use B+ trees, which change two things:

  1. Internal nodes store only keys, never values — they are pure signposts, so more of them fit in one block and the tree gets even shallower.
  2. All values live in the leaves, and the leaves are linked left to right, so a range scan walks the leaf chain without ever climbing back up.

The same keys as above, as a B+ tree — compare with the B-tree at the end of the insertion demo:

\begin{tikzpicture}[
  n/.style={draw,thick,minimum height=0.7cm,font=\small\ttfamily},
  a/.style={->,thick}
]
  \node[n] (r) at (0,0) {10, 20};
  \node[n] (l1) at (-3,-1.8) {5, 6};
  \node[n] (l2) at (0,-1.8) {12};
  \node[n] (l3) at (3,-1.8) {30};
  \draw[a] (r.south west) -- (l1.north);
  \draw[a] (r.south) -- (l2.north);
  \draw[a] (r.south east) -- (l3.north);
  \draw[a] (l1.east) -- (l2.west);
  \draw[a] (l2.east) -- (l3.west);
\end{tikzpicture}
B-tree B+ tree
Values stored every node leaves only
Leaf linkage no yes, left to right
Range scan in-order walk, up and down walk the leaf chain
Fan-out lower (values take space) higher (keys only)
Used by older filesystems InnoDB, PostgreSQL, SQLite indexes

The code

A compact B-tree (order m, simplified — production code also deletes):

class BNode:
    def __init__(self, leaf=True):
        self.keys = []
        self.children = []
        self.leaf = leaf

class BTree:
    def __init__(self, m=3):
        self.m = m
        self.root = BNode()

    def search(self, node, k):
        i = 0
        while i < len(node.keys) and k > node.keys[i]:
            i += 1
        if i < len(node.keys) and k == node.keys[i]:
            return node, i
        if node.leaf:
            return None
        return self.search(node.children[i], k)

    def insert(self, k):
        r = self.root
        if len(r.keys) == self.m - 1:   # root is full: grow the tree
            s = BNode(leaf=False)
            s.children.append(r)
            self._split(s, 0)
            self.root = s
        self._insert_not_full(self.root, k)

    def _split(self, parent, i):
        m, full = self.m, parent.children[i]
        mid = len(full.keys) // 2
        right = BNode(leaf=full.leaf)
        right.keys = full.keys[mid + 1:]
        if not full.leaf:
            right.children = full.children[mid + 1:]
            full.children = full.children[:mid + 1]
        parent.keys.insert(i, full.keys[mid])
        parent.children.insert(i + 1, right)
        full.keys = full.keys[:mid]

    def _insert_not_full(self, node, k):
        i = len(node.keys) - 1
        if node.leaf:
            node.keys.append(None)
            while i >= 0 and k < node.keys[i]:
                node.keys[i + 1] = node.keys[i]
                i -= 1
            node.keys[i + 1] = k
        else:
            while i >= 0 and k < node.keys[i]:
                i -= 1
            i += 1
            if len(node.children[i].keys) == self.m - 1:
                self._split(node, i)
                if k > node.keys[i]:
                    i += 1
            self._insert_not_full(node.children[i], k)

Complexity

Operation Time Disk reads
Search / insert / delete \(O(\log_m n)\) \(O(\log_m n)\) blocks
Range scan of \(k\) rows (B+) \(O(\log_m n + k)\) sequential leaf reads

With \(m\) in the hundreds, \(\log_m n\) is 2–4 for billions of rows — that is the entire point.

Edge cases and where they live