Vineet Ganti
B-Trees and B+Trees: The Structure Under Nearly Every Index
All posts

Data Engineering/Database Engineering · Part 5 of 14

·16 min read

B-Trees and B+Trees: The Structure Under Nearly Every Index

Why databases don't use plain B-Trees, how a B+Tree makes ranges cheap, what real tree pages hold when you open them, and how much a wide key costs. With a working tree you can drive, and a real walk from root to row.

DatabasesPostgreSQLMySQLIndexingData Structures

Post 3 treated an index as a box that finds rows fast. This post opens the box. Nearly every index you'll meet is a B+Tree, a structure built around one goal: find anything with very few page reads.

It's easy to learn this from textbook pictures, with two keys in a node, and come away with the wrong sense of scale. So besides a tree you can drive, this post walks a real index on a million rows, page by page. It took three pages to reach any row.

#Why not just scan?

A table is a file of pages, as post 2 showed. A full table scan pulls pages one by one and checks each row. It costs as many I/Os as there are pages, and the row you want may be on the last one. Databases soften this with parallel workers, but it's still reading everything.

What we need is a way to rule out most of the table without reading it. That's what the B-Tree does. It comes from a paper by Bayer and McCreight, written in 1970.

#The B-Tree

A B-Tree is a balanced tree of nodes:

  • A tree of degree M has nodes with at most M children.
  • A node with M children holds M − 1 elements, each a key and a value.
  • The value is a pointer to the data.
  • The top node is the root, the bottom ones are leaves, and the rest are internal nodes.

The practical rule that makes it fit a database is simple: one node is one page. A single I/O brings in a whole node.

To search, read the root and pick the child whose range contains your key. Each level costs about one page read. Because the tree is balanced, every leaf is the same distance from the root, so there's no unlucky key.

When a page is full, an insert splits it, pushing the middle key up to the parent. If the parent is full it splits too, and if the root splits, the tree grows a level. So a B-Tree grows from the top, which is what keeps it balanced. Post 4 showed why splits are expensive, and why random keys cause so many.

#Two limitations

Values in every node waste space. While walking down you only use the keys, but each internal node also carries values you don't want. Fewer elements fit in a page, so the tree needs more pages and more levels.

Ranges are slow. Keys 4 through 9 are next to each other in sorted order, but they can be scattered across levels. A range scan has to climb back up to a parent between children, reading the same pages again.

#The B+Tree

A B+Tree makes two changes:

  1. Internal pages hold only keys. All values live in the leaves.
  2. Leaves are linked to their neighbours.

The price is that some keys appear twice, once to route and once in a leaf. That's a small cost. The rule for navigating changes a little as well: at a key equal to yours, go right, because the value is in a leaf on that side.

Here are both, working. Each page holds a few keys so that you can see them. A real page holds hundreds. Try this sequence:

  1. Press Fill with ordered keys.
  2. Set the range from 20 to 60 and press Scan range. Note the page reads.
  3. Switch to B-Tree, and scan the same range. It reads far more pages, because it keeps returning to parents.
  4. Try Fill with random keys, and compare the splits and how full the pages are.
Insert keys, or fill the tree, then search it and scan a range.
height 1pages 1splits so far 0pages 0% full
B-TreeB+Tree
Values live inEvery nodeLeaves only
Keys per internal pageFewerMany more
Height for the same dataTallerShorter
Duplicate keysNoSome, in internal pages
Finding one keyCan stop earlyAlways goes to a leaf
Range scanHops around the treeWalks the leaf chain

Nearly all relational databases use the B+Tree. The course points out why the two get confused: the original paper's figures drew only keys, every book copied them, and the difference disappeared.

#A real tree, opened up

Time to leave the toy version. Postgres's pageinspect extension can read index pages directly. Here's a walk through the primary key of a million-row table, from the root to one row, done the way an index scan does it:

✅ ran here · PostgreSQL 18.6 · root to row, on real pages
-- walking the primary key of a 1,000,000-row table to id = 703000
-- the index has 2745 pages, and the root is page 412
page 412   root      level 2  10 entries, separator 625861 points down to page 1842
page 1842  internal  level 1  286 entries, separator 702721 points down to page 1929
page 1929  leaf      level 0  367 entries, key 703000 -> heap address (3799,185)
             leaf neighbours: previous page 1928, next page 1930

SELECT ctid, id, name FROM t WHERE id = 703000;
heap says: ctid (3799,185), id 703000, name 'row 703000'

Three index pages out of 2,745, then one heap page. The numbers show how flat a real tree is:

  • The root has 10 entries.
  • Each internal page has about 286 entries.
  • Each leaf has 367 entries.

Multiply them: 10 × 286 × 367 is about a million. A fourth level would reach hundreds of millions. That's why the depth barely changes as tables grow, and why even a huge index is only a handful of reads away.

The last line of the output is the link to the table: the leaf's value is the heap address (3799,185), and the row is exactly there. The leaf also has neighbours, on both sides. The docs describe each level of the tree as a doubly linked list, not only the leaves.

The leaf chain pays off on a range. 5,001 consecutive ids:

✅ ran here · PostgreSQL 18.6
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF) SELECT id FROM t WHERE id BETWEEN 4000 AND 9000;
                           QUERY PLAN                            
-----------------------------------------------------------------
 Index Only Scan using t_pkey on t (actual rows=5001.00 loops=1)
   Index Cond: ((id >= 4000) AND (id <= 9000))
   Heap Fetches: 0
   Index Searches: 1
   Buffers: shared hit=18
 Planning:
   Buffers: shared hit=77
(7 rows)

18 pages: down the tree once, then along about 14 leaf pages, each holding hundreds of the rows you want. The plan says Index Searches: 1, so the tree was descended once. It's the same walk the simulator showed.

Try it yourself. This box has a real B+Tree in your browser. The last preset follows the leaf links:

Look inside a real B+Treeruns in your browser
100,000 rows and a primary key. These are the index's real pages. In bt_page_items, ctid on a leaf is a heap address, and on an internal page its first number is the child page.
Real PostgreSQL loads when you press Run: about 6 MB, once per visit.

#What a key costs

The number of entries per page is the tree's fanout, and the key's size sets it. Here's the same million rows with four kinds of key:

✅ ran here · PostgreSQL 18.6
SELECT key_type, index_size, pages, height, entries_in_a_leaf
FROM (VALUES ('int, 4 bytes', 'k_int_pkey'), ('bigint, 8 bytes', 'k_big_pkey'), ('uuid, 16 bytes', 'k_uuid_pkey'), ('text, 36 characters', 'k_text_pkey')) AS x(key_type, idx),
LATERAL (SELECT pg_size_pretty(pg_relation_size(idx::regclass)) AS index_size, pg_relation_size(idx::regclass) / 8192 AS pages) s,
LATERAL (SELECT level + 1 AS height FROM bt_metap(idx)) m,
LATERAL (SELECT live_items AS entries_in_a_leaf FROM bt_page_stats(idx, 100)) p;
      key_type       | index_size | pages | height | entries_in_a_leaf 
---------------------+------------+-------+--------+-------------------
 int, 4 bytes        | 21 MB      |  2745 |      3 |               367
 bigint, 8 bytes     | 21 MB      |  2745 |      3 |               367
 uuid, 16 bytes      | 30 MB      |  3853 |      3 |               262
 text, 36 characters | 56 MB      |  7210 |      3 |               141
(4 rows)

Two things stand out.

int and bigint came out identical. 367 entries a page and 21 MB each. Index entries are padded to 8-byte boundaries, so a 4-byte key saves nothing. If you were tempted to use int to keep an index small, the padding has already eaten the saving.

A text UUID is expensive. The 36-character form fits 141 per leaf where an int fits 367, and the index is 56 MB against 21 MB. The binary uuid type is much better at 30 MB. All four are still 3 levels high at a million rows, so lookups cost the same. The difference is memory: a larger index competes for the buffer pool, as the race in post 4 showed.

#What the leaves point to

Here's where engines differ most. The leaf has to lead to the row, and each design does that differently:

In Postgres every index points straight at the row. Reads are direct, and the leaf entry stays small. The cost comes when a row moves: every index may need updating, which is the heart of the Uber story in post 14.

In InnoDB the table is the primary key's tree, and every secondary index holds the primary key. Rows can move freely without touching secondary indexes. The cost is a second tree walk on each lookup, and a key that's copied everywhere. Here's that second cost measured: two tables with the same rows and the same email index, one with an int primary key and one with a text UUID:

✅ ran here · MySQL 8.4.13
SELECT table_name, index_name, round(stat_value * 16 / 1024, 1) AS size_mb FROM mysql.innodb_index_stats WHERE database_name = database() AND stat_name = 'size' ORDER BY table_name, index_name;
+------------+------------+---------+
| table_name | index_name | size_mb |
+------------+------------+---------+
| users_int  | PRIMARY    |    14.5 |
| users_int  | idx_email  |    18.6 |
| users_uuid | PRIMARY    |    24.6 |
| users_uuid | idx_email  |    36.7 |
+------------+------------+---------+
4 rows in set (0.03 sec)

The email index doubled, from 18.6 MB to 36.7 MB, without its own column changing. That's what the course means when it says a primary key choice poisons everything in InnoDB. Every further secondary index pays again.

The course's mitigation is to store UUIDs in binary (16 bytes rather than 36), which helps but stays much bigger than an int.

#Implementation notes

  • Most engines link their leaves, including InnoDB, Postgres and SQL Server. 🎓 The course says MongoDB's WiredTiger omits the links because Mongo doesn't favour key ranges. The WiredTiger docs confirm it's a B-Tree with keys in internal pages and values in leaves, and I couldn't confirm the part about links either way.
  • 🎓 The course also says WiredTiger has an LSM variant. That's about the library rather than MongoDB, which has only used its B-Tree. I couldn't verify its current status, so treat it as unconfirmed.
  • Memory is the real constraint. Internal pages are few and hot, so they usually stay cached, leaving only leaves to be read from disk. With 2,745 pages here, the internal levels are about a dozen pages.
  • 🎓 Trees have to be safe for many threads. The course's last lecture covers how MySQL 8 made InnoDB's B+Tree more concurrent. In 5.6 a structure change locked the whole index, blocking readers. Newer versions added an intent-style SX lock, so that readers can continue while a page split is prepared. I didn't reproduce this, since it needs a contention test.

#Things that can trip you up

  • Tiny diagrams mislead. A real page holds hundreds of entries, so a real tree is very wide and very shallow.
  • bigint doesn't double an index. Padding means int and bigint index entries are the same size here.
  • Index width affects everything above it. A wider key means more pages, and a bigger cache footprint.
  • Never index a blob. Long keys cut the fanout, and Postgres limits an index entry to about a third of a page.
  • Don't choose a text UUID as an InnoDB primary key lightly. It's copied into every secondary index.
  • The planner may still skip your index. A shallow tree doesn't make a million heap visits cheap, as post 3 showed.

#Reproduce this yourself

  1. ✅ Open any index with pageinspect, on Postgres 18:
    sql
    CREATE EXTENSION pageinspect;
    SELECT root, level FROM bt_metap('t_pkey');
    SELECT itemoffset, ctid, data FROM bt_page_items('t_pkey', 412) LIMIT 5;
    
    On an internal page, the first number in ctid is the child page. On a leaf it's the heap page.
  2. ✅ To walk by hand: start at root, find the last entry whose key is at or below yours, and follow it. The data column shows the key as little-endian hex bytes.
  3. ✅ For key sizes, build the same table with int, bigint, uuid and text keys, and compare pg_relation_size and bt_page_stats.
  4. ✅ For the InnoDB test, compare sizes in mysql.innodb_index_stats after ANALYZE TABLE. Each stat_value of size is a count of 16 KB pages.

#Glossary

TermMeaning
B-TreeA balanced tree with keys and values in every node
B+TreeA B-Tree with values only in leaves, and linked leaves
DegreeThe most children a node can have
Root, internal, leafThe top node, the middle nodes, the bottom nodes
FanoutHow many children a page has, which decides the height
Page splitDividing a full page and promoting a key to the parent
Data pointerWhat a leaf uses to reach the row
LatchA very short lock protecting an in-memory structure

#Summary

A B-Tree cuts the search space level by level, with one node per page and every leaf at the same depth. Keeping values in every node wastes space and makes ranges slow, so databases use the B+Tree, where internal pages only route and linked leaves hold everything. Real trees are very flat: a million rows took three levels. Key size sets the fanout, so it decides how much memory an index needs, and InnoDB multiplies that cost across every secondary index.

#Concepts at a glance

ConceptIn one lineWhy it matters
One node, one pageA node read is one I/OWhy tree height is the number that counts
BalanceEvery leaf at the same depthNo unlucky keys
SplitA full page divides and pushes a key upThe expensive part of inserting
Internal pagesKeys only, in a B+TreeMore fanout, shorter tree
Linked leavesEach leaf knows its neighboursRanges become a walk
FanoutEntries per pageSet by key size
Heap addressWhat a Postgres leaf storesDirect reads, but moves are costly
Primary key in the leafWhat an InnoDB secondary storesMoves are cheap, wide keys aren't

#Test yourself

In the real index, why did a million rows need only three levels?

Each level multiplies the reach by the fanout. With a root of 10 entries, internal pages of about 286 and leaves of 367, three levels cover about a million keys. A fourth multiplies that by hundreds again.

Why is a range scan faster on a B+Tree than on a B-Tree?

Keys sit in linked leaves in sorted order, so after finding the first key the scan walks sideways. In a B-Tree adjacent keys can be on different levels, so the scan keeps climbing back through parents and re-reading pages.

What does a B+Tree give up to get those benefits?

Some keys are stored twice, once in an internal page and once in a leaf, the leaf links take a little space, and a search always goes to a leaf rather than stopping early. All of those are small next to fitting far more keys per page.

Why did an index on email double in size when only the primary key's type changed?

In InnoDB each secondary index entry contains the primary key. Changing the primary key from an int to a 36-character string put that string in every entry of the email index.

#Open questions and gaps

  • I read Postgres pages directly, but InnoDB's tree only from size statistics and the docs. I didn't open an .ibd file.
  • I couldn't verify whether WiredTiger links its leaves, or the status of its LSM variant.
  • 🎓 The lecture on MySQL 8's B+Tree latching is reported, not reproduced.
  • The paper is usually dated 1970, when it appeared as a report. It was published in a journal in 1972.

#Sources