Indexing
- Explain how a B+tree lookup and range scan work, and why tree height stays small
- Contrast InnoDB clustered tables with Postgres heap tables and what that means for secondary index lookups
- Order the columns of a composite index for a given query, and decide when to make it covering
- Pick the right index type (B-tree, hash, GIN, GiST, BRIN, partial, expression) for a workload
- Diagnose why an index is not used, and estimate the write cost of adding one
TL;DR
- A B+tree index is a sorted, balanced tree of pages (8 KB in Postgres, 16 KB in InnoDB). High fan-out keeps it to ≈ 3–4 levels even for billions of rows, so a point lookup is a handful of page reads.
- InnoDB tables are clustered by primary key; secondary indexes store the PK and need a second lookup. Postgres tables are heaps; every index points to a physical tuple location (TID).
- Composite index rule: equality columns first, then the range or sort column. Only a leftmost prefix of the index can be used for seeking.
- A covering index (Postgres
INCLUDE, or InnoDB's implicit PK columns) answers the query without touching the table. In Postgres this also depends on the visibility map, so vacuum matters. - Use partial indexes for hot subsets (
WHERE status = 'PENDING'), expression indexes forlower(email), GIN for JSONB/arrays/full text, GiST for ranges and exclusion constraints, BRIN for huge append-only tables ordered by time. - Every index slows every write to its table and competes for memory. Drop the ones
pg_stat_user_indexessays are never used.
Why it matters
Most production database incidents that are not about locking are about missing or wrong indexes: a checkout query that took 5 ms with 100k orders takes 3 seconds at 50 million, the connection pool saturates, and the whole site degrades during a sale. The opposite failure is just as real: a payments table with twelve indexes where each insert does twelve B-tree updates, WAL volume explodes, and replicas lag.
As an architect you are expected to look at a query and its access pattern and say which index serves it, what it costs on writes, and whether the table layout (clustering, partitioning) helps or fights you.
Core concepts
B+tree internals
A B+tree stores keys in sorted order across fixed-size pages:
- Internal pages hold separator keys and child pointers. With 8 KB pages and small keys, a page holds hundreds of entries (fan-out).
- Leaf pages hold every key with a pointer to the row (Postgres: TID = block number + offset; InnoDB secondary index: the PK value; InnoDB clustered index: the row itself).
- Leaves are linked to their siblings, so a range scan descends once and then walks sideways.
Rough arithmetic: with ≈ 300 entries per page, a root points to 300 internal pages, which point to ≈ 90,000 leaves holding ≈ 27 million entries (300³). One more level reaches ≈ 8 billion. The root and internal pages are almost always cached, so a lookup typically costs one or two physical reads.
Inserts go into the correct leaf; when a leaf is full it splits. Sequential keys (identity, UUIDv7, timestamps) always append to the rightmost leaf, which is cache-friendly. Random keys (UUIDv4) insert all over the tree, causing splits, half-empty pages, and a working set the size of the whole index. Postgres B-tree indexes default to fillfactor = 90 to leave room for updates; Postgres also implements the Lehman–Yao variant with right-links so readers do not block on concurrent splits, and since version 13 deduplicates repeated keys in leaves.
Clustered vs heap tables
| Aspect | InnoDB (clustered) | Postgres (heap) |
|---|---|---|
| Row location | Inside the PK B+tree leaf | Unordered heap pages; indexes hold TIDs |
| Secondary lookup | Secondary index → PK → clustered index (two descents) | Index → heap fetch (one descent + one page) |
| PK range scan | Very efficient: rows are physically adjacent | Rows may be scattered unless the table was loaded in order (CLUSTER is a one-off rewrite) |
| Wide PK cost | Copied into every secondary index | Only in the PK index |
| Update of a row | In place in the clustered index, old version to undo log | New tuple version; indexes updated unless it is a HOT update |
Practical consequences: in InnoDB, choose a short, monotonically increasing PK and design composite PKs to cluster rows you read together (for example (account_id, entry_id) keeps an account's ledger entries on adjacent pages). In Postgres, watch the planner's correlation statistic: an index scan over a range is cheap when heap order matches index order and expensive when every row is on a different page.
HOT updates (Postgres). If an UPDATE changes no indexed column and the new tuple fits on the same heap page, Postgres creates a heap-only tuple and does not touch any index. Adding an index on a frequently updated column (updated_at, status) silently disables HOT for those updates and multiplies write cost. Leaving free space with a lower table fillfactor (for example 80–90) makes HOT more likely on update-heavy tables.
Composite indexes and the leftmost prefix
An index on (merchant_id, status, created_at) is sorted by merchant_id, then status within each merchant, then created_at. It can seek on:
merchant_id = ?merchant_id = ? AND status = ?merchant_id = ? AND status = ? AND created_at > ?, and return rows already sorted bycreated_at
It cannot efficiently seek on status = ? alone or created_at > ? alone, because those values are scattered across the tree. Version caveats: MySQL 8.0.13+ and Postgres 18+ can sometimes skip-scan a leading column with few distinct values, but do not design around it.
Column-order heuristics:
- Equality predicates first, then the one range predicate or
ORDER BYcolumn last. After the first range condition, later columns cannot be used for seeking (they can still filter inside the index). - Among equality columns, order by which queries you need to share the index, not purely by selectivity.
(merchant_id, status)also serves "all orders of a merchant". - Match sort direction for multi-column sorts:
ORDER BY created_at DESC, id DESCis served by(created_at, id)scanned backward, butORDER BY created_at DESC, id ASCneeds an index declared(created_at DESC, id ASC).
Example from a payments back office:
-- Query: a merchant's recent failed payments
SELECT id, amount_minor, created_at
FROM payment
WHERE merchant_id = $1 AND status = 'FAILED' AND created_at >= now() - interval '7 days'
ORDER BY created_at DESC
LIMIT 50;
-- Serves it: equality, equality, then range+sort
CREATE INDEX payment_merchant_status_created_idx
ON payment (merchant_id, status, created_at DESC);
Covering indexes and index-only scans
If every column the query needs is in the index, the database can skip the table. In the query above, adding the payload columns makes it covering:
CREATE INDEX payment_merchant_status_created_cov
ON payment (merchant_id, status, created_at DESC)
INCLUDE (id, amount_minor);
INCLUDE (Postgres 11+) stores extra columns in the leaf only: they do not affect ordering and cannot be used for seeking, but they keep internal pages small. In InnoDB every secondary index implicitly contains the PK columns, so an index on (merchant_id, status, created_at) already "covers" id if id is the PK.
Postgres caveat: because visibility information lives in the heap, an index-only scan must check the visibility map. Pages not marked all-visible require a heap fetch anyway (Heap Fetches: N in EXPLAIN ANALYZE). A table with lagging vacuum gets little benefit from covering indexes. See PostgreSQL Deep Dive.
Partial and expression indexes
Partial index: index only the rows a query cares about. A payout job scanning pending payouts from a table where 99.9% of rows are SETTLED:
CREATE INDEX payout_pending_idx ON payout (scheduled_at) WHERE status = 'PENDING';
The index stays tiny and hot, and writes to settled rows do not touch it. The query's WHERE must imply the index predicate (status = 'PENDING' literally, not a parameter that happens to be 'PENDING' in a generic plan). Partial unique indexes enforce rules like "one active cart per customer". MySQL has no partial indexes.
Expression index: index the result of a function, and query with the same expression.
CREATE UNIQUE INDEX customer_email_lower_uq ON customer (lower(email));
SELECT id FROM customer WHERE lower(email) = lower($1);
MySQL 8.0.13+ supports functional key parts (INDEX ((lower(email)))) and indexed generated columns.
Specialized index types
| Type | Structure | Supports | Typical use |
|---|---|---|---|
| B-tree (default) | Balanced sorted tree | =, <, >, BETWEEN, IN, ORDER BY, prefix LIKE 'abc%' (with C collation or text_pattern_ops) | Almost everything |
| Hash | Hash buckets | Equality only | Very long keys compared only by equality; crash-safe in Postgres only since 10. InnoDB does not offer user hash indexes (it has an internal adaptive hash index) |
| GIN | Inverted index: element → posting list of rows | JSONB containment @>, array overlap, full-text search, pg_trgm for LIKE '%term%' | Product attributes in JSONB, tags, search-as-you-type on small catalogs |
| GiST | Balanced tree of bounding predicates | Ranges overlap &&, geometry, nearest-neighbour ORDER BY <->, exclusion constraints | Booking periods, price validity, store locator |
| SP-GiST | Space-partitioned trees | Points, IP ranges, non-balanced data | Niche geometric and prefix data |
| BRIN | Min/max summary per block range (128 pages by default) | Range predicates on columns correlated with physical order | created_at on a multi-terabyte append-only ledger or event log |
BRIN is the underrated one for banks: an index on ledger_entry(created_at) might be several gigabytes as a B-tree but only kilobytes to megabytes as BRIN (rough; it depends on table size and range size). It only works if rows are inserted roughly in time order and rarely updated, which is exactly how ledgers behave. GIN indexes are slower to update; Postgres buffers new entries in a "pending list" (fastupdate) which makes inserts cheaper but searches occasionally slower.
Selectivity and cardinality
Selectivity is the fraction of rows a predicate returns. Indexes win when it is small: random page reads for 1% of a table can be slower than one sequential scan of the whole thing. The crossover depends on row width, caching, storage and correlation, so let the planner decide using statistics, and verify with EXPLAIN ANALYZE (see Query Optimization).
- Low-cardinality columns (
statuswith 5 values,country) are poor standalone indexes, but excellent as a leading equality column in a composite index or as a partial index predicate, especially when the value you query is rare (PENDINGamong mostlySETTLED). - Skewed data matters:
merchant_id = 1(your largest merchant, 30% of payments) andmerchant_id = 98765(ten payments) deserve different plans. Postgres uses most-common-value statistics to tell them apart, but prepared statements with generic plans can pick one plan for both.
Write cost of indexes
Each index adds, per inserted row, a B-tree descent and leaf write, WAL records, and buffer-pool pressure; each update of an indexed column adds a delete-plus-insert in that index (and in Postgres, losing HOT means all indexes get a new entry). A rough mental model: write cost grows roughly linearly with the number of indexes. Unique indexes also add a check that may wait on concurrent inserts of the same key.
Find candidates to drop:
SELECT s.relname AS table_name, s.indexrelname AS index_name,
s.idx_scan, pg_size_pretty(pg_relation_size(s.indexrelid)) AS size
FROM pg_stat_user_indexes s
JOIN pg_index i ON i.indexrelid = s.indexrelid
WHERE s.idx_scan = 0 AND NOT i.indisunique
ORDER BY pg_relation_size(s.indexrelid) DESC;
Check replicas too: an index unused on the primary may serve reporting queries on a standby, and statistics are per server. MySQL 8.0 lets you mark an index INVISIBLE to test the impact of dropping it without actually dropping it.
When indexes are not used
| Cause | Example | Fix |
|---|---|---|
| Function or arithmetic on the column | WHERE date(created_at) = '2025-11-28' | Rewrite as a range: created_at >= '2025-11-28' AND created_at < '2025-11-29', or an expression index |
| Implicit type conversion | MySQL: phone is varchar, query passes an integer | Pass the right type; check driver parameter types |
| Leading wildcard | LIKE '%vina%' | pg_trgm GIN index or a search engine |
| Non-C collation prefix search | LIKE 'abc%' with en_US collation | Index with text_pattern_ops or use C collation for codes |
| Predicate not on leftmost prefix | Index (merchant_id, created_at), query only on created_at | Another index, or reorder |
OR across different columns | WHERE email = $1 OR phone = $2 | Postgres can BitmapOr two indexes; otherwise UNION |
| Low selectivity | Half the table matches | Expected: a seq scan is cheaper |
| Stale or missing statistics | After a bulk load | ANALYZE; tune autovacuum analyze thresholds |
| Small table | A few pages | Expected: the whole table fits in one read |
| Partial index not implied | Generic plan with status = $1 | Use a literal or a custom plan |
Trade-offs
| Option | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| Single-column B-tree | Simple, flexible, composable via bitmap scans | Often not selective enough; extra heap fetches | Unique lookups (email, external_id) |
| Composite B-tree | Serves equality + range + sort in one seek | Order-sensitive; prefix rule limits reuse | Hot, well-known query shapes |
Covering (INCLUDE) | Index-only scans, fewer random reads | Larger index, more write cost; needs vacuum in Postgres | Very hot read queries returning few columns |
| Partial | Tiny, hot, cheap writes for excluded rows | Only serves queries whose predicate implies it; not in MySQL | Queues, pending states, soft-delete filters |
| GIN | Containment, full text, trigram search | Slow updates, large | JSONB attributes, tags, fuzzy text |
| BRIN | Minuscule, nearly free writes | Useful only with physical correlation; lossy | Append-only time-series and ledgers |
| No index | Fastest writes | Every query scans | Write-only tables (raw logs), tiny tables |
In practice
- Design indexes from queries, not columns. For each hot query write down: equality columns, range column, sort, columns returned, rows per call, calls per second. Then build the smallest set of indexes that serves them.
- Index foreign key columns in Postgres (the leading columns of some index are enough), at least wherever the parent rows can be deleted or re-keyed; static lookup references such as
currencyare the usual exception. - Build indexes on live tables with
CREATE INDEX CONCURRENTLY(Postgres) or online DDL (MySQL); a plainCREATE INDEXblocks writes for the whole build. Details in Zero-Downtime Schema Migrations. - Monitor index size versus table size, bloat, and cache hit ratio. Re-create bloated indexes with
REINDEX CONCURRENTLY(Postgres 12+). - For multi-tenant tables,
tenant_idis usually the leading column of every index, matching how every query filters (see Schema Patterns).
A Go helper you might run in CI against a staging database to flag missing FK indexes:
package dbcheck
import (
"context"
"fmt"
"github.com/jackc/pgx/v5/pgxpool"
)
const missingFKIndexes = `
SELECT c.conrelid::regclass::text AS table_name, c.conname
FROM pg_constraint c
WHERE c.contype = 'f'
AND NOT EXISTS (
SELECT 1 FROM pg_index i
WHERE i.indrelid = c.conrelid
AND (i.indkey::int2[])[0:cardinality(c.conkey) - 1] @> c.conkey
)`
// MissingFKIndexes returns foreign keys whose columns are not a prefix of any index.
func MissingFKIndexes(ctx context.Context, pool *pgxpool.Pool) ([]string, error) {
rows, err := pool.Query(ctx, missingFKIndexes)
if err != nil {
return nil, fmt.Errorf("query fk indexes: %w", err)
}
defer rows.Close()
var out []string
for rows.Next() {
var table, constraint string
if err := rows.Scan(&table, &constraint); err != nil {
return nil, err
}
out = append(out, table+"."+constraint)
}
return out, rows.Err()
}
The array check is an approximation (it tests that the FK columns appear in the index's leading positions in any order), which is good enough for a lint.
Common pitfalls
- Indexing every column "just in case". Symptom: insert latency and WAL volume grow with each release; replicas lag during peak.
- Wrong composite order.
(created_at, merchant_id)for a "merchant's recent orders" query. Symptom:EXPLAINshows the index used but with a huge number of rows filtered. - Random UUIDv4 as InnoDB primary key. Symptom: insert throughput falls as the table grows beyond memory; page splits and fragmentation.
- Indexing an often-updated column in Postgres. Symptom:
n_tup_hot_updnear zero, index bloat, write amplification. - Expecting covering indexes to help on a poorly vacuumed table. Symptom: "Index Only Scan" with large
Heap Fetches. - Duplicate and redundant indexes.
(a)is redundant when(a, b)exists (unless(a)is unique or much smaller and very hot). - Plain
CREATE INDEXon a busy table in production. Symptom: writes block for minutes; checkout errors spike. - Wrapping the column in a function in
WHERE(lower,date, casts) without a matching expression index.
Interview angle
- Classic prompts: "This query is slow, what index would you add?", "Why isn't my index used?", "What's the downside of adding indexes?", "UUID or bigint as primary key?"
- A strong answer derives the composite index from the query's equality, range and sort parts, mentions covering, partial and the write cost, and verifies with
EXPLAIN ANALYZErather than guessing. - Show you know the storage difference: in InnoDB the PK is the table; in Postgres indexes point into a heap and HOT updates matter.
- Follow-ups: "How would you index a 5 TB ledger table for date-range audits?" (partitioning plus BRIN or local B-trees), "How do you search product names with typos?" (trigram or a search engine, see Search & Inverted Indexes).
- Red flags: "add an index on every column", not knowing the leftmost-prefix rule, believing an index always makes a query faster.
Self-check
1. Why does a B+tree stay shallow, and why are range scans efficient?
Each page holds hundreds of keys, so each level multiplies capacity by the fan-out; three to four levels cover billions of entries. All values live in leaves, which are linked in key order, so a range scan descends once to the first key and then reads leaves sequentially without returning to the root.
2. In InnoDB, why is a secondary-index lookup more expensive than a PK lookup, and how does that change in Postgres?
InnoDB secondary indexes store the primary key value, so a lookup descends the secondary index, then descends the clustered PK index to fetch the row. In Postgres every index stores the tuple's physical location (TID), so any index lookup is one descent plus a heap page read; PK and secondary indexes are structurally equal.
3. Which index serves WHERE customer_id = ? AND created_at BETWEEN ? AND ? ORDER BY created_at DESC LIMIT 20, and why that order?
(customer_id, created_at) (or created_at DESC). The equality column comes first so the index narrows to one customer's contiguous range, then created_at is sorted within it, which serves both the range filter and the sort, letting the scan stop after 20 rows. Reversed, the index would scan all customers in the date range.
4. What are the conditions for a Postgres index-only scan to actually avoid the heap?
All referenced columns must be in the index (key or INCLUDE columns), the index type must support it (B-tree does; GIN does not), and the heap pages must be marked all-visible in the visibility map, which vacuum maintains. Otherwise the executor still fetches heap pages to check visibility.
5. Scenario: a 4 TB ledger_entry table is append-only; auditors run date-range queries. What indexing would you propose?
Partition by month (see Partitioning & Sharding in Practice) so date filters prune partitions, and on created_at use a BRIN index, which is tiny and almost free to maintain because physical order matches insert time. Keep B-trees only for point-lookup paths such as (account_id, created_at) for statements. Verify with EXPLAIN (ANALYZE, BUFFERS).
6. Why might adding an index on orders.updated_at make writes much slower in Postgres?
Every update changes updated_at, so the update now modifies an indexed column and can no longer be a HOT update. Each update then inserts new entries into every index on the table, not just the new one, multiplying write amplification and bloat.
7. Give three reasons the planner may ignore an index that seems to match.
The predicate wraps the column in a function or cast; the predicate is not satisfied by the index's leftmost prefix; or statistics say a large fraction of rows match, so a sequential scan is cheaper. Others: stale statistics, tiny tables, leading-wildcard LIKE, generic plans that cannot prove a partial-index predicate.
Exercise
Measure, do not guess.
docker run --name pg-idx -e POSTGRES_PASSWORD=pg -p 5432:5432 -d postgres:17
docker exec -it pg-idx psql -U postgres
CREATE TABLE payment (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
merchant_id int NOT NULL,
status text NOT NULL,
amount_minor bigint NOT NULL,
created_at timestamptz NOT NULL
);
INSERT INTO payment (merchant_id, status, amount_minor, created_at)
SELECT (random() * 5000)::int,
(ARRAY['SETTLED','SETTLED','SETTLED','SETTLED','FAILED','PENDING'])[1 + (random() * 5)::int],
(random() * 10000000)::bigint,
now() - (i || ' seconds')::interval
FROM generate_series(1, 5000000) AS i;
ANALYZE payment;
- Run
EXPLAIN (ANALYZE, BUFFERS)on the "merchant's recent failed payments" query with no index; note time and buffers. - Create
(created_at, merchant_id, status), then(merchant_id, status, created_at), and compare the plans and rows filtered. - Add
INCLUDE (amount_minor), runVACUUM payment, and confirm an Index Only Scan withHeap Fetches: 0. - Create a partial index
WHERE status = 'PENDING'and compare its size with a full index onstatususing\di+. - Create
BRIN (created_at)and a B-tree oncreated_at; compare sizes and the plan for a one-hour range. - Measure write cost: time inserting 500k rows with only the PK, then with five indexes.
Done when you can explain, for each step, why the plan changed, using the numbers you recorded.
Further reading
- Markus Winand, SQL Performance Explained and the site use-the-index-luke.com.
- PostgreSQL documentation, "Indexes" chapter: postgresql.org/docs/current/indexes.html.
- MySQL Reference Manual, "Optimization and Indexes" and "Clustered and Secondary Indexes".
- Philip L. Lehman and S. Bing Yao, "Efficient Locking for Concurrent Operations on B-Trees" (1981).
- Martin Kleppmann, Designing Data-Intensive Applications, ch. 3.
Related
- Query Optimization — reading plans to see whether indexes are used.
- Storage Engines: B-Tree vs LSM — the engines underneath these indexes.
- Relational Modeling & Normalization — keys and constraints that become indexes.
- Partitioning & Sharding in Practice — local indexes on partitioned tables.
- Data Structures Inside Real Systems — B-trees, skip lists and Bloom filters in context.
- Search & Inverted Indexes — when a database index is not enough.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).