Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

Part 17 / Topic 1 of 8

How a B-tree works

CREATE INDEX with no type gives you a B-tree: a shallow, sorted tree — root page, a level or two of internal pages, leaf pages holding (value, row-address) pairs in order. Two properties do all the work:

  • Shallow: 100,000 rows is 2–3 levels; even a billion rows is ~4. A lookup reads one page per level — a handful of page reads against a 12,500-page table scan.
  • Sorted: the tree serves not just = but everything order-shaped: <, >=, BETWEEN, prefix LIKE 'abc%' (a range from abc to abd), ORDER BY without sorting, min()/max() instantly.
CREATE INDEX idx_users_email ON big_users (email);
EXPLAIN (COSTS OFF) SELECT * FROM big_users WHERE email = '[email protected]';
EXPLAIN (COSTS OFF) SELECT max(email) FROM big_users;
CREATE INDEX
                     QUERY PLAN                      
-----------------------------------------------------
 Index Scan using idx_users_email on big_users
   Index Cond: (email = '[email protected]'::text)
(2 rows)

                                QUERY PLAN                                 
---------------------------------------------------------------------------
 Result
   InitPlan 1
     ->  Limit
           ->  Index Only Scan Backward using idx_users_email on big_users
                 Index Cond: (email IS NOT NULL)
(5 rows)

What a B-tree cannot serve, because sorting doesn't help: <>, contains-anywhere LIKE '%foo%' (no left edge to descend by — section 6's trigram GIN picks that up), and any condition that transforms the column first — section 4's whole topic.

🧪 Quick quiz — answer from memory, then check.

  1. Why can a B-tree serve BETWEEN and ORDER BY?
  2. Why can't it serve LIKE '%ample%'?
Show the answers
  1. Its leaves are sorted — ranges are contiguous runs, and reading in leaf order is the sort.
  2. There's no leading value to descend the tree with — every leaf could match.

Done here? The practice set for Part 17 — 5 exercises with solutions — is on the part page.

Search the guide