Skip to main content
Code Matrix

How Database Indexes and B-Trees Turn Slow Table Scans Into Millisecond Lookups

Adding an index feels like free speed until writes slow down and composite column order fails to hit. Understand page-aligned B-Trees, O(log n) lookup math, and index design trade-offs.

Published 2026-09-22Updated 2026-11-0810 min read766 words
Table of Contents (7 sections)

When a web app launches with 500 users, every SQL query feels instantaneous: SELECT * FROM orders WHERE email = 'maya@example.com' finishes in 2 milliseconds. Six months later, that table crosses 20 million rows—and suddenly CPU spikes to 100%, pages time out, and dashboards grind to a halt.

The query did not break; the database simply ran out of luck doing Sequential Table Scans across millions of unordered disk pages. Creating a database index solves that bottleneck immediately—yet adding indexes carelessly degrades INSERT throughput and bloats RAM. Knowing how B-Trees store keys explains both the speedup and the hidden cost.

Sequential Scan vs. Indexed Lookup

Without an index on email, PostgreSQL or MySQL has zero shortcut to know which disk block holds 'maya@example.com'. Even if only one row matches, the storage engine must stream every 8 KB / 16 KB page of the table heap from disk/buffer cache and inspect every record linearly (O(n)).

OperationFull Table Scan (20M rows)B-Tree Index (B = 500 fanout)
Algorithmic GrowthO(n) linear readO(log_B n) tree traversal
Pages / Nodes InspectedHundreds of thousands of pages3 to 4 tree levels total!
Lookup ConsistencyDegrades linearly as data growsNearly flat across millions of rows
Write OverheadMinimal (1 heap append)Must update table + every active index

Think about that number: a 4-level B-Tree storing 500 sorted separator keys per 8 KB page can locate any exact row among over 62 billion entries (500^4) in just 4 page reads!

Why Databases Use Wide B-Trees Instead of Binary Trees

Textbooks introduce binary search trees with 2 children per node. Why do real databases like PostgreSQL, SQLite, and InnoDB use B-Trees (specifically B+Trees) packing hundreds of keys inside each node?

Because reading a disk or SSD happens in fixed 4 KB–16 KB pages, not 8-byte pointers. Reading 1 key from disk takes the exact same I/O wait (~100 microseconds on NVMe, ~8 milliseconds on HDD) as reading a full sorted 8 KB page containing 400 keys! By making every tree node fit one disk page with high branching factor ("fanout"), B-Trees keep tree height tiny (depth 3–4 for huge datasets) while keeping parent levels cached permanently inside RAM.

How a B+Tree Separates Navigation From Payload

In modern B+Trees:

  • Internal Nodes hold only sorted routing keys + child page pointers, maximizing how many branches fit inside a single cached page.
  • Leaf Pages store all actual key entries plus row pointers (or clustered row data) linked sideways in doubly-linked lists—making range queries like WHERE created_at BETWEEN '2026-11-01' AND '2026-11-30' fly sequentially across adjacent leaf blocks without re-climbing the tree!

Benchmark Linear Scan vs. Sorted Tree Search in TypeScript

You can measure the exact search-step gap locally over 1,000,000 sorted keys using TypeScript:

ts
// index-lookup-bench.ts — Compare O(n) linear scan vs O(log n) sorted page binary search
interface OrderRow {
  orderId: number;
  amountCents: number;
}

function linearScan(rows: OrderRow[], targetId: number): { found: OrderRow | null; steps: number } {
  let steps = 0;
  for (const row of rows) {
    steps += 1;
    if (row.orderId === targetId) return { found: row, steps };
  }
  return { found: null, steps };
}

function indexedBinaryLookup(
  sortedIndex: OrderRow[],
  targetId: number,
): { found: OrderRow | null; steps: number } {
  let low = 0;
  let high = sortedIndex.length - 1;
  let steps = 0;

  while (low <= high) {
    steps += 1;
    const mid = (low + high) >>> 1;
    const candidate = sortedIndex[mid];
    if (candidate.orderId === targetId) return { found: candidate, steps };
    if (candidate.orderId < targetId) low = mid + 1;
    else high = mid - 1;
  }

  return { found: null, steps };
}

const rows: OrderRow[] = Array.from({ length: 1_000_000 }, (_, i) => ({
  orderId: 100_000 + i * 3,
  amountCents: (i % 90 + 10) * 100,
}));

const target = 100_000 + 890_421 * 3;
console.log("Linear scan:", linearScan(rows, target));       // ~890,422 comparisons
console.log("Indexed lookup:", indexedBinaryLookup(rows, target)); // <= 20 comparisons!

Even before page-level B-Tree fanout drops the hop count down to 3–4, binary search cuts 890,422 comparisons down to under 20 (log2(1,000,000) ~ 20)!

Composite Index Rule: The Leftmost Prefix Principle

Suppose you create a multi-column index on (tenant_id, status, created_at):

  1. Sorted first by tenant_id.
  2. Within identical tenant_id, sorted next by status.
  3. Within identical (tenant_id, status), sorted last by created_at.

Because of that strict lexicographical sort order:

  • WHERE tenant_id = 42 AND status = 'paid' -> Uses index fast!
  • WHERE tenant_id = 42 AND created_at > '2026-11-01' -> Uses tenant_id prefix, then scans matching range.
  • WHERE status = 'paid' alone (skipping tenant_id) -> Cannot use the B-Tree efficiently! Think of trying to find everyone named "Maya" inside a phone book sorted strictly by (LastName, FirstName): jumping straight to the "Maya" entries is impossible without scanning the whole book.

Why Every Index Has a Write & Storage Tax

If indexes are fast, why not index every single column?

  • Write amplification: Every INSERT, DELETE, or UPDATE touching an indexed column must rebalance and dirty every affected B-Tree page on top of writing the main table heap and Write-Ahead Log (WAL). Adding 12 unused indexes can cut write throughput by half.
  • Buffer pool pressure: Indexes compete directly with hot table rows for shared RAM cache. Unnecessary indexes evict active data pages to disk.
  • Read query plans instead of guessing: Always verify with EXPLAIN ANALYZE in PostgreSQL/MySQL whether the optimizer actually picks Index Scan (or Index Only Scan) over Seq Scan.

Key Takeaways

  1. Indexes trade write speed and disk RAM for O(log n) reads: Add indexes to high-frequency query filters, joins, and foreign keys—not blindly to every column.
  2. B+Trees match hardware page sizes: Wide page-aligned branching keeps multi-billion-row trees just 3 to 4 hops deep.
  3. Order composite columns by query prefix & selectivity: Put exact equality predicates (tenant_id, user_id) leftmost before range filters (created_at > ...).
  4. Measure with EXPLAIN ANALYZE: Confirm real production query plans before and after adding any index.

Code Matrix Editorial

Engineering Education & Technical Publications

Code Matrix creates visual technical guides, systems breakdowns, and structured curricula connecting software fundamentals to the physical infrastructure of the modern world.

Continue Reading

Related Deep Dives

Browse all →