B-tree
B-дерево
A balanced search tree that can hold many keys and child links in each node. Databases use it to build indexes that can find a single key or scan a range of keys in order.
Also known as: B+ tree
Why databases use B-trees
A database often reads an index one page at a time. A B-tree packs many sorted keys and child links into each node, which typically fits on a page. Even a large index can be only a few levels deep: one page can tell the database which of many child pages to visit next. That is the main advantage over a binary search tree for page-based storage. The goal is to visit fewer pages, not just to make fewer key comparisons.
How a search works
The search starts at the root. The separator keys in each internal node divide the key space into ranges. If a node has separators 20 and 50, a lookup for 35 follows the child link for the range between them. All leaves are at the same depth, so no branch can turn into a long chain, even when keys are inserted in sorted order.
If an insertion overflows a node, the tree can split it and add a separator to the parent. A split can propagate upward, but the tree gains a level only when the root splits. A page visit is not necessarily a disk read: frequently used pages, such as the root, may already be cached.
B-tree versus B+ tree
In a classic B-tree, both internal nodes and leaves can hold records or references to them. In a B+ tree, internal nodes are for navigation, and the leaves hold the records or references. The leaves are typically linked in key order, so a range scan can descend to its starting key and then move across leaves rather than return to the root for every match. Database documentation often calls an index a “B-tree” even when its layout follows the B+ tree design.
Example: reading a range in order
CREATE INDEX events_start_idx ON events (starts_at);
SELECT id, starts_at
FROM events
WHERE starts_at >= '2025-06-01'
AND starts_at < '2025-07-01'
ORDER BY starts_at;
PostgreSQL creates a B-tree index by default. The index gives the planner a way to seek to June 1, scan forward to July 1, and produce rows in the requested order without a separate sort. That is an option, not a guarantee: if the query returns a large share of the table, scanning the table and sorting the result may cost less than visiting many table pages in index order. Use EXPLAIN to see the chosen plan.
What comes up in interviews
A common question is when to prefer a B-tree over a hash index. A hash index is useful for equality lookups, but it does not maintain the key order needed for a range scan. A follow-up is why column order matters in a composite index. With (account_id, starts_at), one account's events for June form a contiguous range. June events across all accounts generally do not: each account has its own stretch of dates in the index.