03
B-tree in one breath
A balanced tree where each internal node holds ~100–500 keys. For 1 billion rows, the tree is only 3–4 levels deep. Lookup = 3–4 random disk reads + final leaf scan = ~0.5–1ms.
Range scans are the killer feature: find the start, then walk leaf-level siblings. "Give me all orders from May" is one seek + a sequential scan, not a million lookups.
Every index row includes the indexed column(s) + a pointer to the actual row. A "covering index" includes every column the query needs, so you never have to fetch the actual row.
Cursor-based pagination (stable under insert)
-- ❌ OFFSET / LIMIT breaks: new rows shift everyone's view
-- SELECT * FROM posts ORDER BY id DESC LIMIT 20 OFFSET 40;
-- ✓ Cursor (opaque token = last-seen id or (ts, id) tuple):
SELECT id, title, created_at
FROM posts
WHERE (created_at, id) < ($1, $2) -- cursor from previous page
ORDER BY created_at DESC, id DESC
LIMIT 20;
-- Encode cursor as base64(created_at || id); send to client.
-- Stable under concurrent inserts. O(log N) per page via composite index.
CREATE INDEX posts_ts_id_desc ON posts(created_at DESC, id DESC);