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, prefixLIKE 'abc%'(a range fromabctoabd),ORDER BYwithout 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.
- Why can a B-tree serve
BETWEENandORDER BY? - Why can't it serve
LIKE '%ample%'?
Show the answers
- Its leaves are sorted — ranges are contiguous runs, and reading in leaf order is the sort.
- 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.