AlgoPlusAlgoPlus
Learn/Databases
Lesson

B-Tree

The shallow, wide, always-balanced tree databases use for indexes: sorted keys, a few pointers per lookup, and splits that push medians upward.

10 min read Watch it move Build it

A B-tree is the balanced, shallow tree most databases use for indexes. Each node holds a sorted run of keys, so a lookup walks from the root down a handful of child pointers instead of scanning every row. Because it stays only a few levels deep, search and insert are O(log n).

Order and the split rule

The order is the branching factor. This demo uses order 4, so each node holds at most 3 keys. Insert a 4th and the node overflows: it splits in two and promotes its middle key up to the parent. Promoting upward — never sideways — is what keeps every leaf at the same depth.

Inserting 10, 20, 5, 6, 12, 30, 7, 17

  1. 110, 20, 5 fill the root: [5, 10, 20].
  2. 2Insert 6 -> [5, 6, 10, 20] overflows (4 keys). Split, promote the middle key 10, leaving [5, 6] and [20] under a new root [10].
  3. 312, 30 go right of 10 -> [12, 20, 30]; 7 goes left -> [5, 6, 7].
  4. 4Insert 17 -> the right leaf becomes [12, 17, 20, 30] and overflows. Split, promote 20 up to the root, leaving [12, 17] and [30].
Final tree (order 4):

            [10, 20]
           /    |    \
    [5,6,7] [12,17]  [30]

Every leaf is exactly one step below the root — perfectly balanced.
Why so shallow and wide?
Each node is sized to one disk page holding many keys, so a single page read decides among many children. With hundreds of keys per node, even a billion rows sit in a tree only 3-4 levels tall — a handful of reads per lookup.
B+ tree in real databases
Production indexes usually use the B+ tree variant: all keys live in the linked leaf nodes, so a range scan like WHERE age BETWEEN 20 AND 30 just walks the leaf chain after finding the start.
OperationTimeSpace
search · follow child pointers downO(log n)O(1)
insert · may split up the pathO(log n)O(1) amortized
delete · may merge or borrowO(log n)O(1)
range scan · k = rows returned (B+ leaf chain)O(log n + k)O(1)
Check yourself
In this order-4 B-tree, a leaf overflows to [12, 17, 20, 30]. What happens next?