The storage engine can fetch a row once you know its page. Indexing is how the database figures out which page — how it answers WHERE email = ? without reading every row in the table. Every senior engineer has added one. Fewer can say, before shipping it, what fraction of rows it stops paying off at, how much memory it will need at 24 months, which cost class its writes fall into, or what makes an index-only scan quietly stop being index-only. This chapter is those numbers and the failure modes behind them.
An index turns an O(N) scan into an O(log N) seek; that part is not interesting. The model that predicts incidents is sharper: an index is a second, differently sorted copy of some of your data that the engine must keep transactionally in sync on every write. Its read benefit is bounded by how few rows a query touches. Its cost scales with write rate, key width and how much of it must stay in memory. Everything in this chapter is a consequence of those two facts.
Start with the arithmetic nobody does in design reviews: fanout. With 8 KB pages and a narrow key, a leaf holds roughly 400 entries. A billion-entry index is then four levels deep, and everything above the leaves fits in about 50 MB. So on any reasonably sized server, "log N" is a fiction. A cold point lookup costs one leaf read plus one heap read, and the only index pages that matter for capacity planning are the leaves. The corollary: index working set is roughly entries × entry width ÷ fill factor, and key width is the dominant lever. Switch the key from a BIGINT to a 64-byte string and the leaves grow 4×, the tree gains a level, and an inner level that used to be free now competes with table data for the buffer pool.
8-byte key (BIGINT) · ~20 B/entry · fanout ≈ 400
~64-byte key (email, text) · ~80 B/entry · fanout ≈ 100
Inner levels are ~1/fanout of the leaves, so a narrow-key index keeps its whole upper tree in ~50 MB and a cold lookup costs one leaf read plus one heap read. Wide keys add a level and push an inner level into competition with table data. Suffix truncation of pivot keys (Postgres 12+) and prefix compression soften the inner-page cost, never the leaf cost.
On the read side, the index only wins for selective queries, and the crossover comes far earlier than most people assume. Take the planner's own arithmetic. With Postgres defaults (seq_page_cost = 1, random_page_cost = 4) and an illustrative 100M-row table at ~100 rows per page (1M pages), a sequential scan costs about 1M page units. An index scan whose heap order is uncorrelated with the key pays roughly one random page per matching row: 4 × k. The two meet at k = 250k rows, or 0.25% of the table. Past that, the "obvious" index is the slower plan.
Model: seq = pages × 1; uncorrelated index ≈ rows × random_page_cost; bitmap reads each touched page once, in order. Caching, CPU and index-page costs ignored. The shape is real. The exact percentages depend on row width and cache hit rate.
Three things move that line, and all three cause production incidents. Correlation: if the heap happens to be in key order (append-only tables indexed by time), the index scan reads pages nearly sequentially and never loses. The planner knows this from the correlation statistic, and it drifts silently as updates scatter rows. The cost constants: setting random_page_cost ≈ 1.1 for SSDs pushes the crossover to about 0.9%. That is correct for the hardware, but it changes plans fleet-wide in one deploy. Bitmap scans sort the row locations into page order first, which flattens the cliff into a plateau. Between roughly 0.25% and a few percent, all three plans cost about the same. That is the band where a small statistics change (a fresh ANALYZE, a skewed tenant, a parameter value outside the histogram) flips the plan and turns a 5 ms query into a 900 ms one with no deploy to point at. The flip itself belongs to Query Planning (Chapter 5). The point here is that the index's usefulness is a band, not a yes/no.
The mirror-image failure is the index that is chosen because it is ordered, not because it is selective. Take WHERE status = 'failed' ORDER BY created_at DESC LIMIT 20 with an index only on created_at. The planner reasons that if 1% of rows are failed, walking the index backwards finds 20 of them after about 2,000 entries, which is cheap. That estimate assumes the matching rows are spread uniformly along the index. If every failed row is from last March, the walk visits every row since March, each with a heap fetch to test the predicate. Illustratively, on a 100M-row table that is tens of millions of random reads for a query estimated at a few thousand. Nothing about the index is wrong. What happened is that an ordered index plus LIMIT converts an estimation error about where rows are into a latency error of four or five orders of magnitude. The durable fix is an index whose leading column is the filter ((status, created_at)) or a partial index on the rare value, so the walk cannot start in the wrong place.
InnoDB and SQL Server (with a clustered key) store the table as a B-tree on one key; Postgres stores an unordered heap and every index points into it. The choice that matters is not the vocabulary but what a secondary index stores as its pointer. A clustered engine stores the primary key, so a secondary lookup is two tree descents and the pointer never goes stale when a row moves. A heap engine stores a physical location (a 6-byte ctid), so a lookup is one descent plus one page read, and any row movement must be reflected in every index.
That trade shows up in three places people rarely connect. Read cost: a secondary lookup in InnoDB that returns 10,000 rows performs 10,000 clustered-tree descents. With the upper levels cached that is ~10,000 leaf probes, but it is CPU and latch traffic a heap engine does not pay. Update cost: InnoDB updates that do not touch secondary-key columns leave secondary indexes alone, even if the row grows and moves pages. Postgres gets the same property only through HOT (2.6), and loses it the moment the new version does not fit on the same page. Physical order: a clustered table stays in key order forever. A Postgres heap is in insertion order until updates scatter it, and CLUSTER is a one-off, exclusive-lock rewrite that decays immediately. If the hot query is a range scan on something other than the insertion order (all of one tenant's rows, say), a clustered engine with (tenant_id, id) as the PK reads a handful of contiguous pages. A heap reads one random page per row. That single decision can be a 50–100× difference in pages touched for a 1,000-row tenant scan (illustrative: ~10 pages versus ~1,000).
Clustered index · the leaf IS the row
Rows physically stored in key order (InnoDB PK, SQL Server clustered). One per table — the table sorted by that key.
Non-clustered · index → heap
index (by name)
heap (unordered)
Index leaves hold a pointer to the row's location. Many per table. Postgres tables are always heaps.
This distinction ripples everywhere. In a clustered table a secondary index stores the primary key as its pointer, so every secondary lookup does two seeks (index → PK → clustered tree). A range scan on the clustering key is sequential and fast; a range scan on any other column is scattered.
Pointer width is the next bill. In InnoDB every secondary index entry carries the full primary key, so a 36-byte string UUID PK instead of an 8-byte BIGINT adds about 28 bytes to every entry of every secondary index. On an illustrative table with 1B rows and 6 secondaries, that is ~170 GB of extra index before any page overhead. Postgres pays differently. Its pointer is a 6-byte physical ctid, which is cheap but tied to location. A non-HOT update moves the tuple, and every index needs a new entry even if no indexed column changed (the HOT discussion in 2.6 covers this).
The expensive mistake is insert locality, and it hits any B-tree index on a random key, clustered or not. With a monotonic key every insert lands on the rightmost leaf. The hot set is a few pages, and leaves are left almost full. Both InnoDB and Postgres special-case the rightmost split for this reason. With UUIDv4, each insert hits a uniformly random leaf, so the whole index is the working set. Random splits also settle leaves at roughly 69% full (ln 2, the classic steady-state result), which inflates the index by about 40%. The failure is non-linear. Insert latency stays flat while the index fits in the buffer pool, then drops off a cliff when it outgrows memory: every insert becomes a random read plus a later dirty-page write, and the problem looks like disk saturation, not indexing.
Monotonic key (BIGINT, UUIDv7)
all writes → right edge; cold pages stay cold
Random key (UUIDv4, hash)
writes spread uniformly; every page must be resident
last 1–2 pages (~KB)
every leaf (= whole index)
near 100% (rightmost split)
~69% (random splits)
O(tree height) pages
O(index size)
one page dirtied repeatedly
a new random page per insert
Illustrative capacity check: 1B rows × ~40 B/entry ÷ 0.69 fill ≈ 58 GB for one random-key index. With a 32 GB buffer pool, about half of all inserts miss cache on that index alone. A monotonic key needs only the right-edge path resident.
Decision rule: if you need globally unique IDs generated off-database, use a time-ordered format (UUIDv7, ULID, snowflake-style). They keep the uniqueness and restore right-edge locality. The one place random keys are the right call is a distributed store that range-partitions on the key. There, monotonic keys concentrate every write on the last shard, which is the hot-spot problem covered in Replication & Sharding (Chapter 6). Local B-tree locality and global write distribution pull in opposite directions, so decide which one binds before choosing the key.
For any query returning more than a handful of rows, the index descent is noise and the heap fetches are the bill. A query returning 2,000 rows through a non-covering index costs one descent plus up to 2,000 random page reads. The same query through a covering index reads 2,000 entries packed into perhaps 10–20 contiguous leaf pages (illustrative: ~150 entries per leaf). That is a 100× reduction in pages touched, and it is why covering is the highest-leverage tuning move on read-hot tables. INCLUDE columns (Postgres 11+, SQL Server) sit only in the leaves, so they widen the leaf level without widening the inner levels or the sort key.
The width has a price you can compute. Adding a 100-byte payload to a 20-byte entry makes the leaf level 6× larger. On a 200M-row table that is roughly 4 GB becoming 24 GB (illustrative), a larger working set, a larger WAL stream on every insert, and a longer rebuild. A reasonable threshold: cover a query when it is in the top handful by total time and returns more than ~10 rows per call, or when it runs at a rate where even one saved random read matters (a hot point lookup at tens of thousands per second). Covering a query that returns one row saves at most one page read and usually is not worth the width.
Non-covering: SELECT city FROM users WHERE email = ? · index(email) only
Covering: index(email) INCLUDE (city) · index-only scan
If every column a query reads is present in the index, the engine answers it from the index alone — an index-only scan. This eliminates the random table fetches that otherwise dominate the cost of returning many rows. Deliberately widening an index to cover a hot query is one of the highest-leverage tuning moves there is.
The production caveat is not width. "Index-only" is conditional on MVCC visibility. A Postgres index entry carries no visibility information, so an index-only scan can skip the heap only for pages that the visibility map marks all-visible, and only VACUUM sets those bits. InnoDB has the same issue in a different form: if a secondary-index page was modified more recently than the reader's snapshot can trust (its page-level max transaction id), the engine falls back to the clustered record to check visibility. Both engines leave the plan unchanged and do the heap work anyway.
Query latency follows the curve: each heap fetch is a buffer lookup and, on a cache miss, a random read. Alert on the Heap Fetches / rows ratio and on the age of the oldest xmin, not on the plan shape.
That is how a covering index "stops working" with no plan change. In EXPLAIN (ANALYZE) the node still reads Index Only Scan, and only the Heap Fetches counter shows the regression. The usual triggers are a bulk backfill, a hot table whose update rate outpaces autovacuum, or one long transaction (often an analytics session or an idle-in-transaction connection) pinning the xmin horizon so VACUUM cannot mark anything all-visible. Covering indexes therefore pay off on tables that are mostly static per page: append-mostly facts, historical partitions. On a table where every row is updated every few minutes, expect index-only scans to cost almost the same as ordinary index scans, and budget accordingly. Two InnoDB-specific notes. Every secondary index already includes the PK columns, so (email) covers SELECT id … WHERE email = ? at no extra cost. And InnoDB has no INCLUDE, so covering columns must be added as key columns, which widens every inner page as well.
A hash index trades order for a single-probe equality lookup, so it cannot serve ranges, sorts or prefixes, and it cannot enforce UNIQUE in Postgres. The B-tree serves all of those from one structure. The textbook framing, "O(1) versus O(log N)", is the least important thing about the choice, for the fanout reason in 2.1: the B-tree's inner levels are cached, so both structures cost about one page read on a warm system. The places a hash index genuinely wins are narrower. A very wide key (a 200-byte URL, say) is stored as a 4-byte hash code, so the index can be several times smaller than a B-tree on the same column. And a hash index is not ordered, so it has no right-edge hot spot and no ordering to preserve under concurrent inserts.
The counterweights: no ORDER BY, no ranges, no uniqueness, and (in Postgres) no multi-column hash index, so you give up the option of later extending it into a composite. A B-tree on hashtext(url) as an expression index gets most of the size win while keeping every B-tree property except range queries on the original value. That is usually the better call. Note one sharp edge on the B-tree side too: LIKE 'abc%' seeks only when the index's collation sorts bytes in prefix order. In Postgres that means the C collation or a text_pattern_ops index. An index built under a linguistic collation silently cannot serve the prefix query at all.
Hash
B-tree
~1 bucket page
~1 leaf page (inner levels cached)
4-byte hash code
full key (pivots truncated)
impossible
native, both directions
no
only with C collation / pattern_ops
no (Postgres)
yes
very wide keys, equality only
everything else
The B-tree is the default for a reason: it handles equality and ranges and ordering and prefixes. The hash index's real advantage is size on wide keys, and a B-tree expression index on a hash of the column captures most of it.
The hash-versus-B-tree choice matters far less than choosing the right specialised structure when the query shape is not a sorted key. GIN is an inverted index (element → posting list) for arrays, jsonb containment and full-text search. It is fast to read, but writes are expensive, which is why it buffers new entries in a pending list that a surprise cleanup can turn into a latency spike on an unlucky insert. GiST is a balanced tree of overlapping bounding predicates, used for geometry, ranges and exclusion constraints. It is R-tree-like, and Postgres implements its R-tree via GiST. BRIN stores only min/max per block range. It is kilobytes for a terabyte-scale append-only table and useless the moment physical order and key order diverge.
The leftmost-prefix rule is table stakes: (a, b, c) seeks on any leading prefix and cannot skip a. The rule that costs real money is the one after it: the first range predicate ends the seek. Columns after a range column can still filter entries inside the index, but every entry in the range is read. Take WHERE tenant_id = ? AND status = ? AND created_at > now() - '30 days' on a large tenant with 1M rows in the window, 2% of them in the requested status (illustrative). An index on (tenant_id, created_at, status) seeks to the window and reads all 1M entries to return 20,000, roughly 7,000 leaf pages. An index on (tenant_id, status, created_at) seeks straight to the 20,000, roughly 140 leaf pages. Same columns, same size, a 50× difference in pages touched, and the gap grows with the tenant.
So the working heuristic is equality columns first, then at most one range or sort column, then INCLUDE payload. An IN (…) list on a leading column sits in between: most engines turn it into one seek per value, which keeps the columns after it seekable but multiplies the descents. That is fine at 5 values and a real cost at 5,000.
A composite index is sorted by its columns left to right, exactly like a phone book sorted by last name then first name. You can seek on a leading prefix; you cannot skip a leading column. This is why column order in a composite index is a design decision, not a formality — put the columns you filter on equality first, the range/sort column last.
The textbook tie-breaker, "most selective column first", is often wrong. For equality predicates, the order among equality columns barely affects seek cost, because the engine descends on the combined key either way. What order actually decides is which other queries the index can also serve, and whether it can deliver rows in ORDER BY order. The latter matters most for ORDER BY created_at DESC LIMIT 20: an index on (tenant_id, created_at) reads 20 entries and stops. Without the trailing sort column the engine reads every matching row and sorts, and that cost grows with the tenant's size, not the page size. Also note that the prefix rule is softening. MySQL 8.0 and PostgreSQL 18 can skip-scan a missing leading column when it has few distinct values, effectively running one seek per distinct value. That is a planner optimisation to benefit from, not something to design around.
The alternative people reach for is two single-column indexes and letting the planner combine them (BitmapAnd in Postgres, index merge in MySQL). It works, and the cost structure is worth knowing. Each side reads every entry matching its own predicate, so the index cost tracks the least selective input, not the result.
The bitmap plan's index cost scales with each predicate's own selectivity, not with the intersection. That is 200× more index entries read here. It is a good fallback for ad-hoc combinations. It is the wrong plan for a query that runs thousands of times a second.
Decision rule: if a combination of predicates appears in a query in the top ten by total time, it deserves a composite. If combinations are ad hoc (a filter UI with twelve optional facets), single-column indexes plus bitmap combination are the only thing that scales, since composites for every subset would be combinatorial. Watch for the bitmap going lossy: when the bitmap exceeds work_mem it degrades to one bit per page, and the heap recheck then evaluates every row on each flagged page. EXPLAIN reports this as lossy heap blocks, and it is a common reason a facet query is fast in staging and slow in production.
Two neighbours of the composite index often beat it. A partial index (WHERE status = 'pending') turns the "low cardinality is useless" rule upside down: if 0.5% of rows are pending and you only ever query those, the index is tiny, stays hot, and only pays write tax on rows that match. An expression index (lower(email)) is the only way a predicate on a transformed column can seek at all. A plain index on email is invisible to WHERE lower(email) = ?, and that mismatch is one of the most common causes of the "we have an index and it still scans" ticket.
Every index is maintained inside the writing transaction, so its cost lands on commit latency, WAL volume and buffer-pool residency, not on some background budget. The useful question is not "how many indexes" but which cost class each index is in, because the classes differ by two orders of magnitude. A monotonic-key index costs a cached right-edge page and a WAL record. A random-key index costs whatever its leaf-residency probability says. A UNIQUE index adds a mandatory read before the write: the engine must prove the key is absent, which disables InnoDB's change buffer (it only defers maintenance for non-unique secondaries) and, in an LSM engine, turns a blind append into a point read, eroding the write advantage the Storage Engines chapter describes. An inverted index (GIN) on a document column can add dozens of entries per row.
The low-cardinality index is the textbook case of cost without benefit: an index on is_active matches half the table, the planner correctly ignores it, and every write still pays for it. The more common real-world version is subsumed indexes: (a) next to (a, b) next to (a, b, c), each added by a different team for a different query. The narrower two are almost always redundant for reads (the wider index serves every prefix), and exist only as write tax, unless they back a UNIQUE constraint or the width difference is large enough that the narrow one stays cached when the wide one does not.
index kind
page touched
random reads
WAL / write-back
monotonic key (id, created_at)
right-edge leaf, cached
0
1 small record
random key, index fits in memory
random leaf, cached
0
1 record + later page write-back
random key, index 3× memory
random leaf, ~⅔ miss
~0.67
1 record + full-page image after checkpoint
UNIQUE (any key order)
must read leaf to prove absence
≥ miss rate
no deferral (no change buffer)
GIN on array / jsonb / text
one entry per element
varies
N records, or pending-list flush spike
partial, predicate false
not touched
0
0
Count indexes by class, not in total. Eight monotonic indexes can be cheaper to maintain than two random-key indexes that have outgrown memory. Postgres logs a full-page image on the first change to a page after each checkpoint; InnoDB writes every flushed page twice through the doublewrite buffer. Either way, scattered dirty pages cost whole-page writes, not entry-sized ones.
The "N indexes ≈ N× the writes" line understates the problem, because the cost isn't CPU. It is page residency. Illustrative worked example: 5,000 inserts/s, 8 indexes, 3 of them on random-ish keys (UUIDs, emails, hashes) totalling 3× the buffer pool. Each random-key index insert touches a leaf that is resident with probability ~⅓. That gives 5,000 × 3 × ⅔ ≈ 10,000 random reads/s just to find where to insert, plus the same pages written back at checkpoint. The five monotonic indexes cost almost nothing. So when you review index count, ask how many indexes have random insert positions and how their total size compares with memory.
The HOT cliff (Postgres). An update that changes no indexed column, and whose new tuple version fits on the same heap page, is a heap-only tuple update: no index is touched at all. Adding one index on a frequently updated column (updated_at is the classic case) disqualifies every update to that table from HOT. Every update now inserts a new entry into every index on the table. A table with 6 indexes goes from ~1 index write per update to ~6, and index bloat accelerates. The planner's cost estimate for the new index shows none of this. Check n_tup_hot_upd / n_tup_upd before and after, and consider a lower fillfactor on update-heavy tables so HOT has room on the page.
Building the index is its own incident. A plain CREATE INDEX blocks writes for the duration. CREATE INDEX CONCURRENTLY avoids the lock but scans the table twice and must wait out every transaction that could see the old state. One forgotten long transaction stalls it indefinitely. If it fails (a uniqueness violation, a cancelled session) it leaves an INVALID index that the planner never uses but every write still maintains, a pure tax until someone notices. MySQL online DDL buffers concurrent changes in a row log, and a busy table can overflow it and abort the build hours in. Budget the build like a migration, not a config change.
Dead entries at the head of the index. Deleting a row does not remove its index entries. In Postgres they stay until VACUUM, and in InnoDB delete-marked secondary entries stay until purge. B-tree pages are also not merged back when they empty partially: Postgres reclaims only fully empty leaf pages, InnoDB merges only below a fill threshold. The workload that exposes this is the table used as a queue: insert at the right edge, process and delete from the left, poll with ORDER BY id LIMIT 10. Every poll starts at the left edge and must step over every dead entry that has not yet been cleaned up, visiting the heap to learn it is dead unless an earlier scan already marked it (Postgres kill bits, which can only be set once the row is dead to every snapshot).
The cascade is the part to recognise. A long transaction elsewhere pins the cleanup horizon, so dead entries accumulate and cannot even be kill-marked. Poll latency rises linearly with the backlog, workers poll more because each poll returns late, and the extra polls add buffer traffic to a table that is now the hottest in the system. Illustratively, 50,000 un-reclaimable dead entries at the head and 200 polls per second is ten million entry visits per second to hand out a few hundred rows. The fixes are structural: a partial index on the ready state (dead rows leave the index's key range once their status changes, though entries still linger until cleanup), time-partitioning so processed history is dropped rather than deleted, SKIP LOCKED so workers do not queue behind each other, and a hard cap on transaction age on any database that hosts a queue.
The unused-index trap. "Drop indexes with zero scans" is correct advice with two sharp edges. Usage counters are per node: an index idle on the primary may be the only thing keeping a replica's reporting query fast, so aggregate usage across the fleet before dropping. An index backing a UNIQUE constraint can show zero scans because enforcement is not counted as one, and an index on a child foreign-key column may show a handful of scans a month, each of which saved a full child-table scan during a parent delete. Stats resets and quarterly jobs cause the rest of the false positives. Make the index invisible (MySQL) or reversible first, then drop it after a full business cycle.
keep / add
justify it
cut or redesign
< ~0.5%
0.5% – ~5%
> ~5%, uncorrelated
monotonic
few hot ranges
uniform random
< 10%
10 – 50%
> 50% (and random)
never
rarely
yes → kills HOT
yes, avoids sort
partially
no
hot on ≥1 node
periodic job only
zero, not UNIQUE/FK
One pink cell is a conversation. Two or more on a write-heavy table usually means the index is costing more than it returns, or a partial, expression or composite index would serve the same query at lower cost.
Indexing is a portfolio you curate, not a list you append to. Every entry has to justify both its read benefit and its write, memory and operational cost.
The method that survives contact with production starts from the top queries by total time (calls × mean latency), not from columns or from slow-query samples. For each one: equality filters become leading columns, one range or sort column trails them, and the returned columns become INCLUDE candidates if the query returns more than a few rows. Then cost each candidate by class (2.6) and by memory: project its size at 12 and 24 months and add it to the resident set of every other random-key index. Then subtract: merge subsumed prefixes, replace low-selectivity indexes with partial ones, and retire unused ones through the invisible-first path.
Partitioning changes the arithmetic. On a partitioned table, indexes are local to each partition in Postgres and InnoDB. That makes old data cheap to drop and keeps each partition's index small enough to cache. It also has two costs that surface late. A UNIQUE constraint must include the partition key, so "email is unique" on a table partitioned by month cannot be enforced by the database at all. And a lookup that does not constrain the partition key probes every partition: with 365 daily partitions a point lookup by email is 365 index descents plus the planning cost of considering 365 children. The upper levels are cached, so each probe is cheap, but a 0.2 ms lookup becoming 20 ms is a common post-partitioning regression (illustrative). The rule: partition on the key that the hot lookups already carry, and give any other identity lookup its own small unpartitioned mapping table.
An index is a B-tree (Chapter 1's structure) layered over the storage engine, logged through the WAL (Chapter 4), visibility-checked by MVCC (Chapter 3) and chosen or ignored by the planner from statistics (Chapter 5). When an index is added and the query does not speed up, the answer is almost always in that last clause, and Chapter 5 is where it gets opened.
Where the conventional advice is wrong
~0.25%
uncorrelated index crossover (rpc=4)
~50 MB
above the leaves, 1B narrow entries
~69%
leaf fill under random inserts
1 index
on updated_at ends HOT
Questions for the design review
Where next