B-Trees and B+ Trees: Database Index Structures
Understand B-trees and B+ trees for disk-based storage, database indexing, and efficient range queries with O(log n) operations.
B-tree families organize sorted keys into disk pages to reduce index I/O. This guide walks through search, split, and range-scan operations, compares B-tree and B+ tree layouts, and explains how page size, key width, and fill affect fanout.
B-Trees and B+ Trees: Database Index Structures
B-tree-family indexes keep large ordered indexes shallow by storing many separator keys and child pointers in each page. A balanced binary search tree also has logarithmic comparisons, but each pointer traversal may land on another disk page; an unbalanced tree can require O(n) comparisons. A useful height estimate starts with the number of entries per leaf and the number of child pages an internal page can route to.
In a common B+ tree layout, leaf pages hold index entries and internal pages hold separators that route searches to leaves. Linked leaves let a range scan continue from one leaf page to the next. The exact page layout, row storage, and split rules depend on the database engine and index type, so this guide treats the B+ tree as a model rather than a universal implementation.
For a rough height estimate, let N be the number of indexed entries, L the average number of entries per leaf page, and F the average number of child pages per internal page. A simple B+ tree estimate is 1 + ceil(log_F(ceil(N / L))) page levels. For example, if a billion entries average 100 per leaf and internal pages average a fanout of 200, the estimate is about five page levels. Wider keys, row locators, page headers, lower fill, and compression all change L and F; cached pages also mean page levels are not the same as physical reads.
Search, Split, and Range Scan
Imagine an internal page with separators [20 | 40] routing to three leaves: keys below 20, keys from 20 through 39, and keys 40 or above. To find 28, start at the root, follow the middle child pointer, then search that leaf. The search reads one root-to-leaf path; whether each page read reaches storage depends on the buffer cache.
If the middle leaf [20, 24, 28, 32, 36] is full and key 30 is inserted, a B+ tree can split it into [20, 24, 28] and [30, 32, 36], then add separator 30 to the parent. Separator conventions vary by implementation; if the parent is full, its split can propagate toward the root. To scan keys from 24 through 35, first descend to the leaf containing 24, then follow leaf links and stop when the next key exceeds 35.
When to Use
B-trees and B+ trees apply when:
- Database indexing — Ordered lookups, range predicates, and sorted iteration
- Filesystem indexing — NTFS, ext4, and HFS+ use B+ tree variants
- Large datasets on disk — Minimizing disk I/O matters more than memory efficiency
- Range queries — B+ tree linked leaves enable sequential access
- Ordered iteration — Keys can be retrieved in sorted order efficiently
When Not to Use
- In-memory databases (red-black trees or skip lists may be faster due to cache locality)
- Sustained write-heavy workloads may benefit from evaluating an LSM-based index, depending on compaction and read costs
- Equality-only key-value lookups may fit a hash index when the database supports it; hash indexes do not provide ordered scans or range lookups
Architecture: Multi-Way Balanced Trees
graph TD
subgraph Internal["B+ Tree Internal Node"]
I1["[20 | 40 | 60]"]
end
subgraph Leaf["B+ Tree Leaf Nodes (linked)"]
L1["[10-15] -> [20-30] -> [40-50] -> [60-70]"]
end
I1 --> L1
Internal nodes store keys for routing; leaf nodes store actual data pointers and are linked for range access.
Implementation
B-Tree Node
class BTreeNode:
def __init__(self, t, leaf=False):
self.t = t # Minimum degree (defines order)
self.leaf = leaf
self.keys = [] # Key values
self.children = [] # Child pointers
self.n = 0 # Current number of keys
class BTree:
"""
B-tree implementation for educational purposes.
In practice, use database-provided implementations.
"""
def __init__(self, t):
self.t = t # Minimum degree (order = 2t)
self.root = BTreeNode(t, leaf=True)
def search(self, k, node=None):
"""Search for key k, return node if found."""
if node is None:
node = self.root
i = 0
while i < node.n and k > node.keys[i]:
i += 1
if i < node.n and k == node.keys[i]:
return node, i
if node.leaf:
return None
return self.search(k, node.children[i])
def insert(self, k):
"""Insert key k into B-tree."""
root = self.root
if len(root.keys) == 2 * self.t - 1:
new_root = BTreeNode(self.t, leaf=False)
new_root.children.append(root)
self._split_child(new_root, 0, root)
self.root = new_root
self._insert_nonfull(self.root, k)
def _split_child(self, parent, i, child):
"""Split a full child node."""
t = self.t
new_child = BTreeNode(t, leaf=child.leaf)
new_child.n = t - 1
# Copy keys to new child
for j in range(t - 1):
new_child.keys.append(child.keys[j + t])
if not child.leaf:
for j in range(t):
new_child.children.append(child.children[j + t])
child.n = t - 1
child.keys = child.keys[:t - 1]
child.children = child.children[:t]
# Insert median key into parent
parent.keys.insert(i, child.keys.pop(t - 1))
parent.children.insert(i + 1, new_child)
def _insert_nonfull(self, node, k):
"""Insert into non-full node."""
i = len(node.keys) - 1
if node.leaf:
node.keys.append(None)
while i >= 0 and k < node.keys[i]:
node.keys[i + 1] = node.keys[i]
i -= 1
node.keys[i + 1] = k
else:
while i >= 0 and k < node.keys[i]:
i -= 1
i += 1
if len(node.children[i].keys) == 2 * self.t - 1:
self._split_child(node, i, node.children[i])
if k > node.keys[i]:
i += 1
self._insert_nonfull(node.children[i], k)
Common Pitfalls / Anti-Patterns
- Confusing t (minimum degree) with order — B-tree of order m has max m children; t = ceil(m/2)
- Not handling root split — Special case when root is full and needs to become internal
- B+ tree leaf vs internal keys — Internal nodes store separator keys for routing only
- Page size assumptions — Database page size is engine-specific; do not assume it matches the filesystem block size
Quick Recap Checklist
- B-trees store up to 2t-1 keys per node, t-1 to 2t-1 children
- All leaves at same depth (balanced)
- B+ tree: only leaves store data, internal nodes store routing keys only
- B+ tree leaves are linked for efficient range scans
- B-tree-family indexes support ordered access; layout and row storage depend on the engine
Trade-off Analysis
| Aspect | B-Tree | B+ Tree | Notes |
|---|---|---|---|
| Search depth | O(log n) to leaf | O(log n) to leaf | Same asymptotic |
| Range queries | Must revisit parent | Sequential leaf links | B+ tree wins |
| Insert/Split | Split may affect all levels | Same | Similar complexity |
| Storage efficiency | All nodes store data | Only leaves store data | B+ tree wins |
| Pointer overhead | Keys + data in all nodes | Internal nodes only have keys | B+ tree wins |
| Point query speed | Can find at leaf earlier | Always to leaf | B-tree may be faster |
| Leaf scan speed | Non-sequential | Sequential via linked list | B+ tree wins |
Choose an Index for the Workload
| Workload | Starting point | Why | Check before choosing |
|---|---|---|---|
| Equality lookups plus ordered reads or range scans | B-tree-family index | Supports point lookup and ordered traversal | Key width, page fill, write rate, and the engine’s index layout |
| Equality lookups only, with no ordering or range predicates | Hash index, if supported | Hashing targets exact-key lookup | Engine support, collision behavior, and whether future queries need ordering |
| Sustained write-heavy ingestion | LSM-based index | Buffers writes and flushes sorted runs | Compaction cost, read amplification, storage headroom, and range-read latency |
Treat this as a starting hypothesis. Benchmark representative queries and write patterns on the target engine; selectivity, caching, maintenance, and concurrency can change the result.
Real-world Failure Scenarios
-
PostgreSQL index bloat: Frequent updates leave empty space in pages, causing index size inflation. Periodic
REINDEXorVACUUMneeded. -
MySQL InnoDB page splits: Random inserts cause many page splits at intermediate levels, degrading insert performance. Bulk loading or sorted inserts perform better.
-
SQLite B-tree depth growth: With a cold cache, a lookup may need storage reads for pages along its path. The count depends on the index size, page layout, and cache state.
-
MongoDB index selectivity: Low-selectivity indexes (e.g., boolean field) cause full index scans that are slower than collection scans.
-
Hot spot nodes in distributed B+ trees: Cassandra/ScyllaDB partition splits create hot nodes. Partition strategy matters more than tree algorithm.
Interview Questions
A binary tree's two-child structure can require many page traversals, while a page-oriented B-tree routes through many children at each internal page. Height depends on average leaf capacity and internal fanout; key width, page fill, and page overhead change both. Page levels also do not map one-for-one to physical reads because upper pages may be cached.
In a B-tree, all nodes (including leaves) can store data and keys. In a B+ tree, only leaf nodes store data; internal nodes store only routing keys. This means: B+ trees have higher fan-out (more keys per internal node), all leaves at same depth, and efficient range queries via linked leaves. B-trees can find a key without traversing to a leaf.
When a node is full (2t-1 keys) and needs to insert, it splits at the median key. The median key goes to the parent; the left half stays in original node, right half goes to new node. This may cascade—parent might also be full, requiring recursive split. Splits can propagate toward the root, with at most one affected ancestor per level. The actual number of page writes depends on the tree height and implementation.
B+ tree leaves are linked via next/prev pointers. After finding the starting leaf via the tree, a range scan follows links to neighboring leaf pages instead of restarting from the root for each key. The number of storage reads still depends on page placement and cache state; leaf links do not guarantee one disk I/O per page.
A B-tree of order m has a maximum of m children per node. The minimum degree t defines the node capacity as: minimum children = t, maximum children = 2t. Relationship: m = 2t (or close to it depending on implementation). For example, with t=50, each node holds up to 99 keys and up to 100 children pointers.
Red-black trees have two-child nodes, so a lookup may traverse many separately allocated nodes. Page-oriented B+ trees store multiple separators and child pointers per internal page, reducing the number of page levels when the effective fanout is high. Actual levels depend on page size, key and pointer widths, fill, and the number of entries; cached upper pages reduce storage reads further.
Write amplification compares physical writes with the logical data written. B-trees write modified leaf pages and may write additional pages when a split changes parent separators. LSM trees buffer writes before flushing sorted runs, then compact those runs. The write and read amplification of either design depend on the engine, storage, and workload.
Larger keys and row locators leave less page space for other entries, reducing leaf capacity and internal fanout. Estimate using the engine's usable page bytes after headers, separators, pointers, and fill reservation; key width alone does not determine the number of entries. Composite keys add bytes, while supported prefix compression can reduce repeated key data. Covering indexes add their own storage cost even when they avoid a table lookup.
Expected answer points:
- Deletions merge sibling nodes when keys fall below minimum threshold (t-1)
- Coalescence or redistribution handles underfull nodes
- Page reclamation: deleted pages return to free list for reuse
- PostgreSQL VACUUM reclaims dead tuples; MySQL InnoDB purge thread handles deleted records
- Lazy deletion: pages marked deleted but not immediately reused until VACUUM/purge runs
Expected answer points:
- Clustered index: B+ tree leaf pages ARE the data pages; table rows stored in order of index key
- Non-clustered index: B+ tree leaf pages contain indexed key + row pointer to data
- Each table has one clustered index (primary key typically); multiple non-clustered indexes
- Clustered: range queries faster (data already ordered), insert/delete more expensive
- Non-clustered: extra I/O for data lookup via pointer chase
Expected answer points:
- Index bloat: accumulation of dead or reusable pages due to updates/deletes
- Causes: random inserts/deletes leave gaps, update-in-place rewrites pages
- Symptoms: index size larger than necessary, degraded scan performance, increased cache pressure
- Solutions: REINDEX rebuilds index from scratch; VACUUM (PostgreSQL) reclaims dead space
- MySQL InnoDB: OPTIMIZE TABLE reorganizes pages;ibuffg purge thread handles deletions
Expected answer points:
- High fanout: internal pages can route to many child pages
- Estimate leaf pages from entries per leaf, then estimate internal levels from average fanout
- Use effective fanout after page headers, key width, row locators, and fill rather than pointer size alone
- Cache residency can keep root and upper levels in memory, so page levels are not a fixed disk-I/O count
Expected answer points:
- Fill factor: a target for how much of a page to use when building or maintaining an index; defaults and behavior vary by engine
- Higher fill can reduce index size but leave less room for inserts into existing pages
- Lower fill reserves more space but uses more pages and cache
- Choose a target from the insert pattern, then measure page splits, size, and read performance
- For example, PostgreSQL supports a per-index fillfactor option; consult the engine documentation for its exact behavior
Expected answer points:
- Unique index: each key appears exactly once in tree; enforced at insert time
- Non-unique index: duplicate keys allowed; typically handled by appending row IDs
- B+ tree stores (key, row_pointer) tuples; for duplicates, uses (key, transaction_id) or list pages
- Unique constraint check traverses tree O(log n) then verifies no match at leaf
- Non-unique: may need to scan all matching entries for query execution
Expected answer points:
- Leaf pages store sorted keys; adjacent keys often share common prefixes
- Prefix compression: store first key fully, subsequent keys store only differing suffix
- Example: ["apple", "apricot", "banana"] becomes ["apple", "-ricot", "banana"]
- Reduces leaf page space by 20-40% depending on key prefix similarity
- Decompression needed on read; trade-off between CPU and I/O savings
Expected answer points:
- LSM trees: writes go to memory (MemTable), then flushed to SSTables on disk
- B+ trees: in-place writes; page splits cause random I/O
- LSM tree write amplification: 1 (data written once), B+ tree: 3-10x
- B+ tree read amplification: O(log n), LSM tree: O(log n) + K (K = number of SSTables)
- LSM trees: better for write-heavy workloads; B+ trees: better for read-heavy or mixed
Expected answer points:
- Covering index: query can be satisfied entirely from index pages without touching table
- All referenced columns included in index key or stored as included columns
- Query executor does index lookup, reads leaf nodes only — no row pointer chase to heap
- PostgreSQL: "Index Only Scan"; MySQL: "Using index" in EXPLAIN
- Trade-offs: larger index, slower inserts/updates, but faster reads for covered queries
Expected answer points:
- Buffer pool (innodb_buffer_pool_size, shared_buffers) caches B+ tree pages in memory
- Hot pages: root, intermediate nodes cached; leaf pages loaded on demand
- Cache hit ratio determines effective I/O cost; 99% hit ratio = 1% disk reads
- LRU or clock-sweep eviction policies manage buffer pool pages
- Prefetching: sequential leaf scans pre-load adjacent pages into buffer pool
Expected answer points:
- Sequential IDs (auto-increment): inserts go to rightmost leaf page — minimal page splits
- GUIDs (UUIDs): random insertion point causes page splits throughout tree
- Random GUIDs: write amplification high, index bloat higher, cache efficiency lower
- Solutions: UUID v7 (time-ordered), UUID v1 with node ID, COMB (sequential GUIDs)
- PostgreSQL: gen_random_uuid(); MySQL: UUID() — both random by default
Expected answer points:
- Latch coupling: B+ tree operations acquire locks on nodes being modified
- Read-write locks: readers share, writers exclusive; prevents dirty reads
- Lock escalation: fine-grained node locks scale better than table-level locks
- Write-write: page split or merge requires parent lock during modification
- PostgreSQL: Heap Only Tuple (HOT) updates avoid index maintenance when possible
- MySQL InnoDB: gap locks and next-key locks for isolation; reduces deadlocks but adds contention
Further Reading
- Database Indexing Deep Dive — How indexes work in practice
- Comparing B-Trees and LSM Trees — Write-optimized alternatives
- B-Tree Visualization — Interactive B-tree operations
- Understanding B+ Tree Clustered vs Non-Clustered Indexes — SQL Server perspective
Conclusion
B-tree-family indexes keep ordered lookups practical by routing through pages with many separators. In a B+ tree layout, linked leaves help range scans continue without restarting at the root for each key. Page levels, storage reads, and write costs depend on the engine and workload. To continue, see composite indexes, covering indexes, and how query planners choose an index in the Database Indexing Deep Dive.
Category
Related Posts
Arrays vs Linked Lists: Understanding the Trade-offs
Compare arrays and linked lists by access, edits, memory use, and cache behavior, with one operation matrix and a reproducible benchmark for real workloads.
Arrays in Python: Indexing, Matrices, and Windows
Learn Python 3 list indexing, 2D matrix traversal, and a sliding-window pattern with runnable exercises for learners who know loops and functions.
AVL Trees: A Hands-On Guide to Rotations
Learn AVL insertions and deletions through height and balance-factor traces, then use a compact Python implementation and compare tree choices.