Chapter 9 of 12
Course Progress0 of 12 completed (0%)

SQL & Relational Database Mastery · Chapter 9 · ~15 min · Advanced

Indexes & The B-Tree Engine: O(log n) Lookups & Storage

Understand how B-Tree indexes search in O(log n) time, compare clustered vs secondary indexes, and master the leftmost prefix rule.

  • Understand how B-Tree index structures navigate millions of records in O(log n) disk page reads
  • Distinguish Clustered Indexes (table layout) from Secondary Indexes (pointer lookups)
  • Master the Leftmost Prefix Rule for composite multi-column indexes
  • Evaluate index trade-offs: read acceleration vs write amplification (INSERT/UPDATE/DELETE cost)

Indexes & The B-Tree Engine: O(log n) Lookups: learn it visually

Understand how B-Tree indexes search in O(log n) time, compare clustered vs secondary indexes, and master the leftmost prefix rule.

Indexes & The B-Tree Engine: O(log n) LookupsUnderstand how B-Tree indexes search in O(log n) time, compare clustered vs secondary indexes, and master the leftmost prefix rule.UNDERSTANDIndexesFOLLOW THE FLOWB-Tree EngineAPPLY ITLookupsIndexes & The B-Tree Engine: O(log n) LookupsUnderstand how B-Tree indexes search in O(log n) time, compare clustered vs secondary indexes, and master the leftmost prefix rule.UNDERSTANDIndexesFOLLOW THE FLOWB-Tree EngineAPPLY ITLookups

1Intuition: Why Binary Trees Don't Work on Disk

In introductory computer science, binary search trees (BSTs, Red-Black trees) are celebrated for O(log₂ n) search. But on physical spinning hard disks or NVMe SSDs, a standard binary tree is a performance disaster: with only two children per node, searching 10 million records requires ~24 separate random disk page reads.

Relational databases solve this with B+ Trees. Instead of two children, each B-Tree node is sized to fit an exact operating system disk block (typically 8 KB or 16 KB) and holds hundreds of keys (a fan-out of 300 to 1,000). A 3-level B-Tree can index tens of millions of records while requiring only 2 or 3 page reads.

High Fan-Out

Hundreds of pointers per node keep tree depth shallow (almost always 3 or 4 levels maximum, even for terabyte datasets).

Sequential Leaf Linking

All leaf pages are linked in a bidirectional doubly-linked list, allowing blazing fast range scans without traversing up and down the tree.

Buffer Pool Caching

The root node and top branch levels are tiny and stay permanently pinned in RAM buffer cache, making most index lookups require only 1 disk read.

Concept Check

A B-Tree index has an average page fan-out (branching factor) of 100. With a root node and 3 levels of depth (height = 3), how many leaf records can it index?

2Architecture: Clustered Tables, Composite Keys & The ESR Rule

Designing effective indexes requires understanding how the database physically stores and orders data on disk. Explore the 3 crucial index architecture models below:

Wrong idea: Adding indexes to every single column speeds up everything

INSERT 1 row → Update 30 separate B-Trees on disk
❌ Write Amplification: Massive I/O bottlenecks and lock contention

Believing that indexing all 30 columns creates a magical fast database. In reality, every index requires separate disk pages, locks, and duplicate writes on every INSERT.

Real system: Strategic B-Tree indexes convert O(N) scans into O(log N) navigations

100M Rows: Root → Branch → Leaf = 3 Page Reads
✅ O(log N) Precision: Microsecond lookups without touching unneeded pages

A 3-level B-Tree with fan-out 500 navigates 125 million rows in exactly 3-4 disk block reads, reducing queries from 45 seconds down to 0.4 milliseconds.

-- The ESR Rule (Equality, Sort, Range) for Composite Indexes:
-- 1. Equality columns first: WHERE tenant_id = 42 AND status = 'active'
-- 2. Sort columns second: ORDER BY created_at DESC
-- 3. Range columns last: AND total_amount BETWEEN 100 AND 500

CREATE INDEX idx_orders_tenant_status_created_amt
ON orders (
    tenant_id,      -- Equality (=)
    status,         -- Equality (=)
    created_at DESC -- Sort (ORDER BY)
    -- Range predicates can be appended at the end
);
Concept Check

You create a composite index on (department_id, hire_date, salary). Which of the following queries CANNOT use this index efficiently?

3Interactive Visual: The B-Tree Search Engine & Write Amplification

Watch how the database traverses root, branch, and leaf nodes to locate specific records in microsecond page reads. Use the slider below to experiment with the trade-off between read acceleration and write overhead.

Interactive B-Tree Engine & Write Amplification Lab

Target Key: #42
Level 0: Root Page (Memory Pinned)
[Keys: 25 | 50 | 75]
Route: Child 2 (25..49)
Level 1: Branch Page (Disk I/O #1)
[Keys: 32 | 40 | 48]
Binary search identifies leaf pointer in 12 CPU cycles
Level 2: Leaf Page (Disk I/O #2 — Row Payload / Clustered Heap)
Target Record #42 Located!
Total page reads: 3 pages (24 KB total) vs 1,200,000 pages (9.6 GB) for full table scan.
2 Secondary Index(es)
Read Latency (SELECT WHERE):
1.0 ms

✅ B-Tree index seek accelerates query by 320x

Write Cost Multiplier (INSERT / UPDATE):
2.9x I/O Cost

✅ Healthy balance for mixed OLTP traffic

Concept Check

What is a 'Covering Index' (Index-Only Scan)?

4Bug Hunt: Craft Optimal Composite Index for Multi-Tenant Query

A high-traffic e-commerce SaaS platform is experiencing severe CPU spikes. A key dashboard query filters orders by tenant_id and status, sorting by created_at DESC. The existing index is inverted, forcing the engine to do an expensive file-sort. Formulate the optimal composite index.

SQL Bug Hunt · Optimal Composite Index Formulation
SQL

🎯 Find and fix the bugs in the code above, then press Run & verify to test your solution.

Need a hint?

• Apply the ESR rule: equality columns first, then sort column.

• Define index on (tenant_id, status, created_at DESC).

• Name index idx_orders_tenant_status_created.

Concept Check

Why does adding 10 secondary indexes to a high-throughput payments table degrade system performance?

5Recap & Index Optimization Rules

  • O(log n) Page Reads: High-fanout B-Trees allow searching hundreds of millions of rows in 3 or 4 disk I/O operations.
  • Leftmost Prefix Discipline: Multi-column composite indexes can only be utilized if the leading leftmost columns match the query predicates.
  • The ESR Heuristic: Place Equality predicates first, Sort columns second, and Range predicates third.
  • Covering Index Power: Eliminate table heap lookups entirely by including all projected columns in the index.
  • Write Amplification Guardrail: Never index indiscriminately. Every secondary index adds synchronous write overhead to every single INSERT, UPDATE, and DELETE statement.

Ready for Chapter 10 (Reading Execution Plans & Query Tuning)? Mark as complete:

Enjoying this free lesson? Your support helps us build more free animated chapters.

Support Us