skip to content

b+trees

wide and short, grows at the root, every leaf at the same depth. build one, a key at a time.

address
everything.index_internals.b_plus_trees
part
part 13, inside indexes
chapter
chapter 1 of 12
reading time
11 min

a B+tree keeps every key in its leaves, in order, with the leaves linked left to right. the pages above them hold only separator keys that say which child to go down. it's wide (hundreds of keys a page) and short (three or four levels for millions of rows), and it grows at the root, so every leaf is always the same distance from the top.

the picture

you know how an index is a sorted copy of a column with an address per row? sorted is easy when it fits on one page. the trouble starts at page two. a sorted array would have to shift half its entries for every insert, and a plain binary tree would be twenty levels deep, one page read per level.

a B+tree is the fix, and it's the shape of a phone book's thumb tabs. the tabs (the root) say "A to F, G to M, N to Z". each section (an inner page) has its own tabs. the actual names and numbers (the keys and their row addresses) are only on the bottom pages, the leaves, and when you finish one page you just turn to the next one (the sibling link) without going back to the tabs.

build one. type a key and press insert, or pick a preset and step. the model holds 4 keys a page, so it splits often enough to watch. (to write one yourself, build a toy database does it in javascript, over real pages.)

rules =
keys =
key =
emptyroot,a leaf
height 1 · leaves 1 · keys 0 · full leaves 0%

emptyan empty index is one leaf page with room for 4 keys.

step 1/33
model of a B+tree, textbook rules, 4 keys a page
insert keys and step. a full leaf splits in two and copies its first right-hand key up as a separator; a full inner page splits and moves its middle key up. when the root splits, a new root appears on top. try a range like 3..9: one trip down, then right along the sibling links.

three things to notice while you play:

  • all the keys are in the leaves. a separator like 5 in the root is a copy. the real 5 lives in a leaf, next to its row address. that's the "+" in B+tree. (a plain B-tree keeps each key exactly once, wherever it lands, inner pages included.)
  • the tree never grows downward. a leaf that fills up splits sideways, and pushes one key into its parent. only when the root itself splits does the tree get taller, and then every leaf gets one level deeper at once. that's why the height counter only moves when you see "root split", and why the tree is always balanced without anybody rebalancing it.
  • a range scan goes down once. after that it walks the leaf level left to right. no climbing back up.

why it stays so short

the lab holds 4 keys a page. postgres holds hundreds. an int4 entry in a leaf is a 16-byte index tuple plus a 4-byte line pointer, so about 400 of them fit in an 8 KB page, and an inner page points at about as many children. every level multiplies the reach by a few hundred:

sqlempty db · ext=pageinspect
CREATE TABLE k1 AS SELECT generate_series(1, 1000) AS id;
CREATE TABLE k100 AS SELECT generate_series(1, 100000) AS id;
CREATE TABLE k1m AS SELECT generate_series(1, 1000000) AS id;
CREATE INDEX k1_id ON k1 (id);
CREATE INDEX k100_id ON k100 (id);
CREATE INDEX k1m_id ON k1m (id);
SELECT i AS index, m.level + 1 AS levels,
       pg_relation_size(i) / 8192 AS pages
FROM unnest(ARRAY['k1_id', 'k100_id', 'k1m_id']) AS i,
     bt_metap(i) AS m
ORDER BY pages;
output, from postgres 18.6
#1 · SELECT 1000
#2 · SELECT 100000
#3 · SELECT 1000000
#4 · CREATE INDEX
#5 · CREATE INDEX
#6 · CREATE INDEX
#7 · SELECT 3
indextextlevelsint8pagesint8
k1_id25
k100_id2276
k1m_id32745
(3 rows)

a thousand keys: a root over a few leaves. a hundred thousand: still two levels: 276 pages are the metapage, the root and 274 leaves. a million: three levels, 2,745 pages. (bt_metap counts levels from the leaves up, starting at 0, so the query adds 1.) three levels of int keys reach into the tens of millions before a fourth is needed. that's the whole trick: the height grows with the logarithm of the row count, base "a few hundred".

predict the output
a lookup by id in the 1,000,000-row index (three levels). how many index pages does it read?
sql
SELECT id FROM k1m WHERE id = 777777;
sqlempty db
CREATE TABLE k1m AS SELECT generate_series(1, 1000000) AS id;
CREATE INDEX k1m_id ON k1m (id);
VACUUM ANALYZE k1m;
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT id FROM k1m WHERE id = 777777;
output, from postgres 18.6
#1 · SELECT 1000000
#2 · CREATE INDEX
#3 · VACUUM
#4 · EXPLAIN
Index Only Scan using k1m_id on k1m (actual rows=1.00 loops=1) Index Cond: (id = 777777) Heap Fetches: 0 Index Searches: 1 Buffers: shared hit=1 read=3 Planning: Buffers: shared hit=11

Buffers: shared hit=1 read=3: four pages, one of them (the metapage) already in memory. it's an index-only scan, so the table isn't touched at all.

a real one

the lab is a model. here's the real thing: postgres's btree (the code calls it nbtree), 200 int keys, built with fillfactor = 10 so that a tiny index spreads over several leaves instead of one.

T1CREATE INDEX t_id ON t (id) WITH (fillfactor = 10)
12336… 33 more383939404174… 33 more7677… 3 more pages191192193198… 5 more2003977115153191rootleaves
child and sibling linkshigh key

CREATE INDEX sorts the 200 keys and writes the leaves left to right, then the root above them.

step 1/2
real output, postgres 18.6 (PGlite 0.5.12) · real-tree
a real nbtree: the root (page 3) over six leaves. every leaf but the last ends in a high key, the smallest key that can't be on that page. the root has one more downlink than separators: its first one has no key at all.

same shape as the lab: a root, a row of leaves, separators that are copies of leaf keys. the details are where postgres differs from the textbook. read the root raw:

sqlempty db · ext=pageinspect · session real
CREATE TABLE t (id int);
INSERT INTO t SELECT generate_series(1, 200);
CREATE INDEX t_id ON t (id) WITH (fillfactor = 10);
SELECT root, level FROM bt_metap('t_id');
SELECT itemoffset, ctid AS downlink, data
FROM bt_page_items('t_id', 3)
ORDER BY itemoffset;
output, from postgres 18.6
#1 · CREATE TABLE
#2 · INSERT 0 200
#3 · CREATE INDEX
#4 · SELECT 1
rootint8levelint8
31
(1 row)
#5 · SELECT 6
itemoffsetint2downlinktiddatatext
1(1,0)''
2(2,1)27 00 00 00 00 00 00 00
3(4,1)4d 00 00 00 00 00 00 00
4(5,1)73 00 00 00 00 00 00 00
5(6,1)99 00 00 00 00 00 00 00
6(7,1)bf 00 00 00 00 00 00 00
(6 rows)

on an inner page, the ctid column isn't a row address: it's the child page number (the second number means nothing here). item 1 points at page 1 and has no key. that's the "minus infinity" item: everything smaller than the first real separator goes left, whatever it is, so there's nothing to store. the separators that follow are 27 hex (39), 4d (77), 73 (115) and so on, little-endian ints padded to 8 bytes.

now a leaf, its first and last items, and every page's sibling pointers:

sqlempty db · ext=pageinspect · session real
continues session real (1 earlier block run first)
SELECT itemoffset, ctid, htid, data
FROM bt_page_items('t_id', 1)
WHERE itemoffset <= 3 OR itemoffset >= 38
ORDER BY itemoffset;
SELECT blkno, type, live_items, btpo_prev AS prev, btpo_next AS next
FROM bt_multi_page_stats('t_id', 1, -1)
ORDER BY blkno;
output, from postgres 18.6
#1 · SELECT 5
itemoffsetint2ctidtidhtidtiddatatext
1(0,1)null27 00 00 00 00 00 00 00
2(0,1)(0,1)01 00 00 00 00 00 00 00
3(0,2)(0,2)02 00 00 00 00 00 00 00
38(0,37)(0,37)25 00 00 00 00 00 00 00
39(0,38)(0,38)26 00 00 00 00 00 00 00
(5 rows)
#2 · SELECT 7
blknoint8typecharlive_itemsint4prevint8nextint8
1l3902
2l3914
3r600
4l3925
5l3946
6l3957
7l1060
(7 rows)

item 1 of leaf 1 is 39, and it has no htid: it doesn't point at a row. it's the page's high key, an upper bound. every key on the page is below it (the last real key is 38, at item 39), and 39 is where the next leaf starts. the stats show the other half: every page knows its left and right neighbour (prev, next, 0 meaning none), and the rightmost leaf (page 7) has no high key, which is why it has 10 items for 10 keys while the others have 39 for 38.

1… 36 more3839… 2 more pages115… 36 more152153… 1 more pages191… 8 more2003977115153191rootleaves
child and sibling linkshigh keysearch path
real output, postgres 18.6 (PGlite 0.5.12) · real-tree
a lookup for 115 on the real tree: the root says 115 ≤ k < 153, so down to page 5, where 115 is the first key. the separator in the root is a copy of it.

the textbook, and what postgres adds

the textbook B+tree (Bayer and McCreight's B-tree, 1972, with the keys moved down to linked leaves) is what the lab draws under "textbook". switch the lab to "postgres nbtree" and three things change, all from one 1981 paper, Lehman and Yao's "efficient locking for concurrent operations on B-trees":

textbook B+treepostgres nbtree
sibling linksleaves only, often one wayevery level, both ways (btpo_prev, btpo_next)
page boundimplied by the parent's separatorsstored on the page: the high key
the first childa key per child, or a special casea "minus infinity" downlink with no key
ascending insertssplit 50/50, leaving half-empty leavessplit near the end, leaving the left page 90% full
underfull pagesmerged with a neighbourleft alone; only a completely empty page is removed, by VACUUM
duplicatesone entry per rowone key with a list of row addresses (postgres 13+)

the right links and the high key exist for concurrency. a reader in the textbook tree has to lock a page and its parent on the way down, so a split can't happen under its feet. a reader in nbtree locks one page at a time: if a split moved its key away while it was between pages, the high key tells it ("115 is past my bound") and the right link says where to go. b-trees under concurrency walks through it. the 90/10 split is page splits, the duplicates are deduplication, and every field of every page is in a real b-tree, page by page.

one level deeperwhy separators are copies, and how postgres shortens them

a leaf split has to tell the parent where the new page starts, and the cleanest boundary is the first key of the right page. copying it up, instead of moving it, keeps the rule simple: every key is in exactly one leaf, and inner pages are only signposts. a separator doesn't even have to be a real key, just something between the last key on the left and the first on the right. postgres uses that pg 12+: for a multicolumn index it keeps only as many columns as it needs to tell the two pages apart (suffix truncation), so inner pages hold more downlinks and the tree stays shorter. for one int column there's nothing to cut, which is why the separators above are exactly 39, 77, 115.

keylines

  • a B+tree keeps every key in the leaves, sorted and linked; inner pages hold separator copies.
  • it grows at the root, so every leaf is always at the same depth.
  • hundreds of keys a page: a million int keys is three levels, four page reads.
  • a range scan goes down once, then walks right along the leaves.
  • postgres adds Lehman and Yao's right links and high keys on every level, plus a key-less first downlink.