SQL & Relational Databases (50 Qs)•Part 2: Core Architecture & Implementation (Mid-Level)
How does a B-Tree (and B+ Tree) Index work internally?
senior LevelMost AskedCode ExampleSystem DesignDatabases & SQLData Structures
In Simple Words: Relational databases store table indexes using self-balancing search trees (primarily B+ Trees):
- Root and Internal Branch Nodes: Store routing keys and child page pointers to direct traversals.
- Leaf Nodes: Hold the actual keys in sorted sequential order, connected horizontally via doubly linked lists.
- Search Efficiency: Finding any record among millions of rows requires only 3 to 4 page reads ($O(\log N)$ tree depth).
- Range Queries: The linked leaf nodes allow blazing fast range scans (
WHERE age BETWEEN 20 AND 30) simply by finding the lower bound and scanning across leaf pointers.
text
B+ Tree Architecture:
[ Root Node: 50 ]
┌───────┴───────┐
▼ ▼
[ Branch: 20 ] [ Branch: 80 ]
┌──────┴──────┐ ┌──────┴──────┐
▼ ▼ ▼ ▼
[Leaf: 10,15] ──► [Leaf: 20,30] ──► [Leaf: 80,90] (Linked Leaf Nodes!)