B-tree
medium 26 minA B-tree is a sorted, always balanced tree with hundreds of keys in each page-sized node.
Video lesson · Chapter 1 of 5
Where can forty-two still be?
Four hops to one row in a billion
1:20Reel coming soon
Theory
Read or listen first. About 2 min.
What it is
A B-tree is a search tree whose nodes are as large as a disk page. Each node holds many sorted keys and one more child pointer than keys, so every step of a search rules out almost everything.
It balances itself: every leaf has the same depth. Search, insert and delete take logarithmic time. Databases mostly use the B+ tree variant, where internal nodes only guide the search and the leaves hold the entries in one linked, sorted row.
Why it exists
A binary tree over a billion keys is 30 levels deep. If each level is a page that must come from disk, one lookup costs 30 slow reads. Packing hundreds of keys in one page makes the tree four levels deep.
Keeping the keys sorted matters as much as finding them. A sorted index answers equality, ranges, prefixes, minimum, maximum and ordering with one structure.
A short history
1970
Rudolf Bayer and Edward McCreight of Boeing present "Organization and maintenance of large ordered indices", the paper that introduces the B-tree.
1973
An IBM article describes the index behind the VSAM access method, which a later survey counts among the early B+ trees.
1979
Douglas Comer's survey "The Ubiquitous B-Tree" appears. The title says how far the structure had spread.
Words to know
- Fan-out
- How many children a node has. High fan-out means few levels.
- Order m
- The largest number of children a node may have, so at most m - 1 keys.
- Root, internal node, leaf
- The top page, the guiding pages in between, and the pages at the bottom.
- Split
- A full node becomes two, and a key moves up to the parent.
- Underflow
- A node with fewer keys than allowed after a delete. It borrows or merges.
- B+ tree
- Variant with all entries in the leaves, and the leaves linked in order.
- Clustered index
- An index whose leaves hold the whole rows.
How it works
Step through the idea, or press Play.
Compare inside one page. Binary search among hundreds of sorted keys
Understand it
Start here
The signpost story
A hiker looks for hut 42. Nobody checks every hut. At each crossing a signpost says which numbers lie in which direction. It is the same with a library directory that says A to M left, N to Z right: each sign leads to a smaller sign, until you stand in front of the book.
Signs are cheap to read. Walking to each crossing is what takes time, like reading a page from disk.
The idea
Why not a binary tree?
Binary: one key per node
B-tree: many keys per node
Self-balancing
All leaves have the same depth. No branch grows long.
High fan-out
Often hundreds of children per node, depending on key size.
Made for pages
One node fills one page of 4 to 16 KB, so one step is one read.
Sorted
Ranges, prefixes, minimum, maximum and ORDER BY come free.
Structure
The rules for order m
| Rule | In general | Order 4 |
|---|---|---|
| Most children of a node | m | 4 |
| Most keys in a node | m - 1 | 3 |
| Fewest keys, not the root | ceil(m / 2) - 1 | 1 |
| Keys in the root | 1 to m - 1 | 1 to 3 |
| Children of a node with k keys | k + 1 | 3 keys, 4 children |
| Leaves | All at the same depth | Always balanced |
A node with the keys 25, 50, 75 has four pointers: below 25, between 25 and 50, between 50 and 75, above 75. In a plain B-tree a search can stop at a key in any node. In a B+ tree a key equal to a separator continues to the right.
Size
How deep is it?
Fan-out and levels
Levels by number of entries
| Entries | Binary | Fan-out 100 | Fan-out 400 | Fan-out 1,000 |
|---|---|---|---|---|
| 1,000 | 10 | 2 | 2 | 1 |
| 1,000,000 | 20 | 3 | 3 | 2 |
| 1,000,000,000 | 30 | 5 | 4 | 3 |
How much must stay in memory?
Where the pages of one lookup live
Search
Find 42
- 1
Root: 25, 50, 75
42 lies between 25 and 50. Take the second pointer.
- 2
Internal: 30, 40
42 is larger than 40. Take the last pointer.
- 3
Leaf: 41, 42, 44
Found. If 42 were not here, it would not exist.
Inside a page the keys are sorted, so a binary search takes a few comparisons in memory. Compared with loading a page, that costs almost nothing.
Insert
The middle goes up
Insert
Order of arrival matters. Keys that arrive in order always go to the last page. InnoDB then leaves pages about 15/16 full; with random keys they are between 1/2 and 15/16 full. Random keys also touch pages all over the disk, which is why random identifiers make a clustered table slower to load.
Delete
Borrow or merge
| Case | What happens |
|---|---|
| Key in a leaf, enough keys left | Remove it |
| Key in an internal node | Replace it with its predecessor or successor from a leaf, then remove that one |
| Underflow, a sibling has spare keys | Borrow one through the parent |
| Underflow, no spare keys | Merge with the sibling and pull the separator down |
| The root has no keys left | Its only child becomes the root: one level less |
B+ tree
All entries in the leaves
B+ tree
- Entries only in the leaves
- Leaves linked in order, often both ways
- More separators fit in a page, so more fan-out
- Range scans go sideways
- Every lookup has the same length
Plain B-tree
- Entries in all nodes
- No leaf links needed
- A lookup may end early, near the root
- No key is stored twice
- A range must walk up and down
Range from 35 to 75
Why databases like it
Linked leaves
Fast range scans.
Thin upper levels
No rows there, so more keys per page.
Neighbouring pages
Reading ahead is possible.
Same depth
Predictable number of reads.
Cost
Time and page reads
| Operation | Comparisons | Page reads |
|---|---|---|
| Search | O(log n) | O(log_f n) |
| Insert | O(log n) | O(log_f n) |
| Delete | O(log n) | O(log_f n) |
| Range of k entries | O(log n + k) | O(log_f n + k / f) |
In a database
From the index to the row
In a clustered index the leaf holds the row. InnoDB stores its tables that way, ordered by primary key. A secondary index leaf holds a reference, so a lookup continues at the row: one more step. If the index holds every column the query needs, that step is saved; such an index covers the query. More on queries in SQL databases.
Limits
When B-trees struggle
| Situation | Why | Think about |
|---|---|---|
| Heavy small writes | One 100-byte change can rewrite an 8 KB page, about 80 times as much | Batching, or an LSM tree |
| Append-only logs and metrics | Time order makes other structures cheaper | LSM tree, partitions by time |
| Random keys | Pages all over the tree are dirtied and split | Ordered identifiers |
| Very long keys | Low fan-out, deeper tree | A shorter key or a hash of it |
| Scans of most rows | Index hops cost more than reading in order | Full scan, or a column store for OLAP |
Which structure?
Summary
The whole topic in one minute.
A B-tree turns one disk page into one decision among hundreds of ranges. Four such decisions find a row among a billion, and the upper levels are small enough to stay in memory, so often only one page is read from disk.
Inserts split full pages and push a key up; deletes borrow or merge. The price is paid by writes: small changes scattered over many pages. When writes dominate, an LSM tree may serve better.
- One node is one page with hundreds of sorted keys.
- A billion entries need about four levels, and the upper ones fit in memory.
- A full node splits and the middle key goes up; the tree grows at the root.
- Deletes borrow from a sibling or merge.
- B+ trees keep entries in linked leaves, which makes ranges cheap.
- Small scattered writes are the weak side.