Sub topic 3
Inside a B-tree index
This chapter assumes you know basic SQL, what a primary key is, and the difference between linear and logarithmic growth. It also assumes you have seen why a full table scan slows down as a table grows. Here you will learn how a B-tree index is built from pages, how a search moves through it, and how inserts change it. The examples use PostgreSQL, but the structure is nearly the same in MySQL (InnoDB), SQL Server, Oracle, and SQLite.
Pages are the unit of storage
A database reads and writes storage in fixed-size blocks called pages. PostgreSQL uses 8 KB pages by default, and InnoDB uses 16 KB. A B-tree index is a set of pages organized as a tree. Each page holds many entries, and each entry is a key (the indexed value) plus a pointer.
What the "B" stands for is debated, and it doesn't matter here. In practice, nearly every database index called a B-tree is a B+tree, a variant where all row pointers live in the bottom level. This chapter uses "B-tree" to mean that variant.
There are three kinds of pages:
- The root page is the single entry point. Every search starts here.
- Internal pages sit between the root and the bottom. Their entries hold a key and a pointer to a child page. They only guide the search.
- Leaf pages are the bottom level. Their entries hold a key and a pointer to the table row, such as a physical row location in PostgreSQL.
Real pages hold hundreds of entries. The diagram shows three per page so that it stays readable.
Separator keys and routing
An internal page stores separator keys that split the key space into ranges. In the diagram, the internal page with keys 30 and 60 says: values below 30 go to the first child, values from 30 up to 60 go to the second, and values of 60 or more go to a third child. The exact boundary rules differ by engine, but the idea is the same.
To find key 260, the database does this:
- Read the root. 260 is at least 100 and less than 500, so follow the pointer in the middle range.
- Read that internal page. 260 is at least 200 and less than 350, so follow the second child.
- Read the leaf page. Search inside it, usually by binary search, and find 260 with its row pointer.
- Follow the row pointer to the table page that holds the full row.
Each step reads one page, so the cost is the height of the tree plus one table page.
Why the tree stays shallow
Pages are large and keys are small, so each page has a high fanout, which is the number of children per internal page. Take a bigint key in an 8 KB page. Each entry takes roughly 16 to 24 bytes with its overhead, so one page holds a few hundred entries. The table below assumes a fanout of 300, which is a round, plausible number.
| Levels of pages | Approximate maximum entries |
|---|---|
| 1 (the root is also a leaf) | 300 |
| 2 | 90,000 |
| 3 | 27,000,000 |
| 4 | 8,100,000,000 |
Each added level multiplies capacity by the fanout. This is why index lookups scale logarithmically: a table with a billion rows needs only about four page reads to find one key. The root and the upper internal pages are touched by almost every query, so they usually stay in the database's memory cache. In practice a lookup often costs one or two real disk reads.
The tree is also balanced. Every leaf is at the same depth, so no key is much slower to find than any other. The engine maintains this property on every insert and delete.
Looking at a real index
PostgreSQL's pageinspect extension exposes the structure. It normally requires superuser rights. This script builds a one-million-row table, indexes it, and reports the tree's height and size.
CREATE EXTENSION IF NOT EXISTS pageinspect;
CREATE TABLE events (
id bigint PRIMARY KEY,
customer_id bigint NOT NULL,
payload text NOT NULL
);
INSERT INTO events
SELECT g, g % 50000, repeat('x', 20)
FROM generate_series(1, 1000000) AS g;
CREATE INDEX events_customer_idx ON events (customer_id);
-- "level" is the height above the leaf level (0 means the root is a leaf).
SELECT level, root FROM bt_metap('events_customer_idx');
SELECT pg_size_pretty(pg_relation_size('events_customer_idx')) AS index_size,
pg_size_pretty(pg_relation_size('events')) AS table_size;Expect a level of 2 or 3 for a million rows. The index will be noticeably smaller than the table, because it holds only the key and a pointer per entry, not the whole row. That size difference is part of why scanning an index is cheaper than scanning the table.
Leaf pages are linked
Leaf pages are chained to their neighbors, in both directions in most engines. This is what makes range scans cheap. For a condition like customer_id BETWEEN 100 AND 200, the database descends the tree once to find the first matching leaf entry. It then walks along the leaf chain until the keys exceed 200. It does not climb back up to the root for each page.
The same chain gives sorted output for free. Leaf entries are stored in key order, so a query with ORDER BY customer_id can read the index in order and skip a separate sort. The chain can be walked backward as well, so ORDER BY customer_id DESC is served too.
Inserts and page splits
The tree stays ordered and balanced because inserts go to a specific leaf. The key's value determines which one. If the leaf has room, the entry is placed in sorted position and nothing else changes.
If the leaf is full, the engine performs a page split:
- Allocate a new page.
- Move about half of the entries to it.
- Add a separator key for the new page to the parent.
- If the parent is now full, split it too. A split can propagate up to the root.
When the root itself splits, the engine creates a new root above it. This is the only way the tree gets taller. The tree grows from the top, so all leaves stay at the same depth.
Fill factor, deletes, and dead space
Many engines let you leave free space in pages when building an index. In PostgreSQL this is the fillfactor storage parameter, which defaults to 90 for B-trees. A lower value leaves room for future inserts and delays splits. The cost is a larger index.
CREATE INDEX events_customer_ff_idx
ON events (customer_id) WITH (fillfactor = 70);Deletes do not immediately shrink the tree. In PostgreSQL, deleting or updating a row leaves its index entry in place until vacuum removes it. Pages that become completely empty can be recycled, but pages that are only partly empty usually stay as they are. Over time, heavy churn can leave an index with many sparse pages, called bloat. Chapter 15 covers detecting and fixing bloat.
Duplicate keys and NULLs
A non-unique index holds many entries with the same key. They sit next to each other in the leaves, so an equality search finds the first one and reads forward until the key changes. PostgreSQL 13 and later also deduplicates: it stores a repeated key once with a list of row pointers, which shrinks indexes on low-variety columns.
NULLs are stored in PostgreSQL B-tree indexes and sort at one end of the order (after all other values by default). So WHERE col IS NULL can use the index. Behavior varies in other engines. Oracle, for example, omits entries where all indexed columns are NULL.
What a B-tree is good at
The structure explains which operations an index serves:
- Equality (
=) andINlists: one descent per value. - Ranges (
<,>,BETWEEN) and prefix matches on text, if the collation allows it: one descent, then a leaf walk. - Sorting and
MIN/MAX: read from the end of the leaf chain.
Anything that does not respect the key order, such as a search on the middle of a string, cannot use the tree to narrow down the search. The next chapters build on this: composite indexes extend the key to several columns, and the planner weighs these costs when deciding whether to use an index at all.
Exercise
A B-tree has a fanout of 200 and a root page that is not a leaf. About how many entries can a tree with three levels of pages hold, and why does a lookup in it need about three index page reads?
Show answer
Three levels hold about 200 x 200 x 200 = 8,000,000 entries. A lookup reads one page per level, the root, one internal page, and one leaf, so it reads three index pages, and then fetches the table row. Adding a fourth level would multiply capacity by 200 again for just one more page read.
Exercise
Why does a range query such as WHERE customer_id BETWEEN 100 AND 200 need only one descent from the root, instead of one descent per matching row?
Show answer
Leaf pages are stored in key order and linked to their neighbors. The database descends once to the first matching leaf entry and then follows the leaf chain until the keys pass 200. It never has to return to the root.