Currently Available: Need a skilled Software Developer for your next project?
Categories
Databases PostgreSQL

Inside PostgreSQL B-Tree Index Implementation

In PostgreSQL, a B-tree index helps a query find rows by their indexed values without scanning the whole table. The index stores those values in sorted pages linked as a tree. Entries on the leaf pages point to table rows, and they usually do not contain the rows themselves.

The section title “64.4. Implementation” comes from the PostgreSQL 14 manual. This article follows that version’s documentation, since some low-level details change between PostgreSQL releases. When PostgreSQL splits a page while other queries are reading the index, it uses links between neighboring pages and boundary keys so those queries can keep going. PostgreSQL also removes obsolete entries and combines duplicate keys to manage space. Together, these behaviors explain how lookups, range scans, and updates work.

What the tree stores

A B-tree index begins with a metadata page that stores information such as the location of the root page, where searches start. Internal pages guide searches toward the leaf pages. They hold pivot entries, which are key boundaries pointing to pages one level lower in the tree. Leaf pages hold entries that point to table rows using tuple IDs (TIDs), which identify where PostgreSQL stores each row.

At each level, every page links to its neighboring pages in both directions, forming a doubly linked list. According to the PostgreSQL 14 implementation documentation, leaf pages typically make up more than 99% of an index’s pages. Most index activity, including scans that return rows in order, happens on these leaf pages.

As a search moves down the tree, PostgreSQL compares the search value with the pivot entries. Once it reaches a leaf page, it finds entries with matching values. If the query needs the row data, PostgreSQL follows those TIDs to the table. For context on which workloads suit this index structure, see when to use PostgreSQL B-tree indexes.

How searches survive page splits

When a new entry will not fit on a leaf page, PostgreSQL splits that page and moves some entries to a new neighboring page. The old page keeps a high key, which marks the upper boundary of the values it holds, and a right link pointing to the next page. These two pieces let a search recover if it lands on the old page after the split.

A search might follow a pointer from a parent page that led to a leaf before the leaf split. If the search value is greater than that leaf’s high key, PostgreSQL follows the right link and checks the next page. It repeats this check as long as the search value exceeds the current page’s high key. Because of this, the parent pointer can briefly remain unchanged after a split without causing the search to miss the matching value. The B-tree implementation README describes this link-and-check approach.

A PostgreSQL server process, called a backend, holds page-level read locks while it examines a page. The lock stops another backend from modifying that page during the read. Because these locks protect only one page at a time, sibling links and high keys let searches move between pages without waiting for PostgreSQL to update every parent pointer first.

After a split, PostgreSQL adds a downlink, which is a pointer to the new child page, to the parent page. If the parent has no room, PostgreSQL splits it too, and it can repeat this up the tree. If the root splits, PostgreSQL creates a new root above the two pages created by the split.

When PostgreSQL splits a leaf page, it sometimes shortens pivot entries by leaving out key attributes that are not needed to separate the values on the two pages. Shorter pivots let each internal page point to more child pages. Because the space saved depends on the keys and page contents, shorter pivots do not guarantee a measurable performance gain for every index. PostgreSQL assumes a page can hold at least three items: one high key and two data items. As a result, PostgreSQL limits any single index entry to approximately one-third of a page.

Duplicate keys and posting lists

When many rows share the same indexed value, PostgreSQL can save space through deduplication. It stores the key values once and groups the matching TIDs in a sorted array. PostgreSQL calls this compact entry a posting-list tuple.

PostgreSQL runs deduplication lazily. When a new entry will not fit on a page, PostgreSQL first checks whether removing entries frees enough space. If that does not clear enough room, PostgreSQL can combine matching entries into a posting list. This cuts down on space used by repeated keys, though the amount you save depends on how many duplicates the index holds. PostgreSQL 14 disables deduplication for some index definitions, including indexes with INCLUDE columns and certain data types or collations. Check the version-specific documentation to see whether a particular index can use it.

How PostgreSQL handles obsolete entries

When you update a row, PostgreSQL can create a new stored version of that row and a matching index entry, even when the indexed value stays the same. PostgreSQL keeps the older entry until it is safe to remove. As obsolete entries pile up, scans have more index entries to check.

PostgreSQL cleans up obsolete entries in several ways. During a scan, it can mark an entry’s line pointer as dead. A later insert can then remove entries already marked dead when a page is close to splitting. PostgreSQL 14 also introduced bottom-up index deletion. This targeted pass tries to clear obsolete entries left by updates from a leaf page before the page splits unnecessarily. Its rules do not catch every removable entry, so it can delay some splits without guaranteeing that an index will stop growing.

VACUUM still performs broader index cleanup, and bottom-up deletion does not replace it. Even when VACUUM or bottom-up deletion cleans up an index, PostgreSQL does not necessarily shrink the index file on disk. Instead, it marks cleaned-up pages as available for reuse. The PostgreSQL 14 documentation explains these cleanup methods and their limits.

Why PostgreSQL keeps some empty pages

PostgreSQL does not routinely merge partly full pages after deletion. If PostgreSQL moved live entries between pages that cover established ranges, concurrent scans could miss or revisit entries. PostgreSQL removes a page only when it is completely empty. It unlinks the page from its neighbors separately from marking it ready for reuse. The page can stay linked to its siblings for a short time, which gives a search that already reached it a safe way to continue.

Because of this, a tree does not necessarily get shorter as soon as many rows disappear. The implementation README describes a fast-root pointer that lets searches skip levels containing only one page. In practice, when you delete rows, PostgreSQL does not immediately shrink the index file or shorten the tree.

What this means for index maintenance

PostgreSQL uses deduplication to reduce repeated key storage in indexes with many duplicate values, though how much space you save depends on your data and index definition. When rows are updated often, PostgreSQL can use bottom-up deletion to avoid some leaf splits caused by obsolete entries. VACUUM still handles broader cleanup, and neither method guarantees a smaller index file on disk.

High keys and right links let searches move past page splits while other queries read the index. PostgreSQL removes obsolete entries and empty pages only when it can do so safely. Meanwhile, PostgreSQL records changes in its write-ahead log (WAL) so it can replay them during recovery after a crash. Because of WAL, PostgreSQL does not have to write structural changes across multiple pages in one indivisible step.

What I'm building

Delegate tasks. Get software.

Give Vroni a GitHub issue, bug report, spec, or rough idea. It reads the repo, plans the change, writes code, runs checks, and works toward a review-ready pull request.

Take a look at vroni.com

Email updates

Usually a new article and a few links I found interesting.

No spam. Unsubscribe with one click.

Leave a Reply

Your email address will not be published. Required fields are marked *