Sub topic 3
Inside a B-tree Index
Assume you know basic SELECT, WHERE, ORDER BY, primary keys, and the difference between linear and logarithmic work. This chapter focuses on how a database index stores keys and finds rows internally.
The shape of a B-tree
A B-tree is a balanced search tree designed for storage devices. It stores many keys in each node, rather than putting one key in each binary-tree node. Database systems usually store each node in a fixed-size page, such as an 8 KiB disk page.
A typical B-tree has three levels of objects:
| Part | Purpose |
|---|---|
| Root page | Starts every search |
| Internal pages | Direct the search toward the correct key range |
| Leaf pages | Store indexed keys and references to table rows |
The tree stays balanced: every leaf is at the same depth. A search therefore follows a predictable path from the root to a leaf.
How a point lookup works
Suppose you create this index:
CREATE INDEX orders_customer_id_idx
ON orders (customer_id);For this query:
SELECT *
FROM orders
WHERE customer_id = 42;The database compares 42 with separator keys in the root page. It chooses the child page whose range could contain 42. It repeats that comparison on each internal page until it reaches a leaf page.
The leaf contains an index entry for the key 42. That entry also identifies the matching table row. In PostgreSQL, this reference is commonly a tuple identifier, or TID. The database follows the TID to fetch the row from the table.
The work is approximately logarithmic in the number of index entries. Because each page contains many entries, a large index can often be searched with only a few page reads.
How range scans work
B-trees keep keys sorted. After finding the first key in a range, the database can read nearby leaf entries in order:
SELECT *
FROM orders
WHERE customer_id >= 40
AND customer_id < 50;Database B-trees commonly connect neighboring leaf pages with sibling links. This lets the engine continue through the range without returning to the root for every key. The same ordering can also help with some ORDER BY operations.
Keeping the tree balanced
When a leaf page becomes full, the database splits it into two pages and copies a separator key into the parent. If the parent is full, that split can continue upward. A root split creates a new root and increases the tree's height.
Splits preserve search correctness, but they require extra page writes. Random insert patterns can cause more scattered pages, while sequential keys often have a more predictable insertion location.
Exercise
Why can a B-tree find a range of keys efficiently after locating the first matching key?
Show answer
Its leaf entries are sorted, and neighboring leaf pages are linked, so the database can scan forward through the range instead of searching from the root for every key.