Skip to content

Indexes

An index is a sorted structure mapping key values to row locations, maintained on every write. The whole discipline is one trade: faster reads, slower writes and more disk. Interviews test whether you know which reads get faster — the answer is narrower than most candidates think.

“A B-tree index stores keys in sorted order across pages, so a lookup is a few page reads instead of a full scan, and it can serve ORDER BY without a sort. A composite index on (a, b) is usable only if you constrain a — it behaves like an index on (a) plus a sorted index on (a, b), which is why column order matters and why equality columns come before range columns. A covering index includes the selected columns so the query never touches the table. Indexes stop helping when the predicate matches a large fraction of the table, when the column is wrapped in a function, or when the types do not match. Every index costs write throughput, so the goal is the smallest set that serves the real queries — verified with EXPLAIN, not guessed.”

A B-tree keeps keys sorted across pages with a shallow tree of internal nodes. A lookup descends the tree — three or four page reads for millions of rows — then either returns the row pointer or walks the leaf level in order for a range. That is why B-trees serve =, <, >, BETWEEN, IN, IS NULL and LIKE 'prefix%' (but not LIKE '%suffix', which has no sorted prefix to seek).

Type Serves
B-tree The default: equality, ranges, sorting
Hash Equality only
GIN jsonb, arrays, full-text search — “contains”
GiST Geometry, ranges, nearest-neighbour
BRIN Very large, naturally ordered tables — tiny, coarse
CREATE INDEX idx_books_author_date ON books (author_id, published_on);

This serves WHERE author_id = 42, WHERE author_id = 42 AND published_on > '2024-01-01', and WHERE author_id = 42 ORDER BY published_on. It cannot efficiently serve WHERE published_on > '2024-01-01', because the leading column is unconstrained.

Think of a phone book sorted by (surname, first name): you can find “all Smiths” and “Smith, John”, but not “all Johns”.

  1. Equality columns first. WHERE status = 'x' AND created_at > y wants (status, created_at).
  2. Range column last. Once the scan hits a range on created_at, later columns cannot narrow it.
  3. Then sort order. ORDER BY created_at DESC is free with (status, created_at DESC).
  4. Low-cardinality columns alone are poor. A boolean column halves the table at best, and the planner will prefer a sequential scan.

If the index contains every column the query needs, the database answers from the index alone — an index-only scan, with no heap access.

CREATE INDEX idx_books_author_title ON books (author_id) INCLUDE (title);
SELECT title FROM books WHERE author_id = 42; -- index-only scan

INCLUDE columns live in the leaf pages but do not affect ordering, so they do not widen the search key. Two costs: a wider index on every write, and in PostgreSQL the visibility map must be current (autovacuum has to keep up) for the scan to actually skip the heap.

Selectivity is the fraction of rows a predicate eliminates. email = ? on a unique column returns one row — excellent. status = 'active' where 95% of rows are active eliminates almost nothing, so the planner scans sequentially: following millions of row pointers is slower than reading pages in order.

  • Low-cardinality columns earn their keep inside a composite index, or as a partial index for a hot subset:
CREATE INDEX idx_jobs_pending ON jobs (run_at) WHERE finished_at IS NULL;

Partial indexes are smaller, cheaper to maintain, and directly serve the query with the same filter.

  • Every write pays. INSERT, UPDATE and DELETE maintain every index on the table.
  • Disk and cache. Indexes compete with the table for memory.
  • Unused indexes. Check pg_stat_user_indexes for idx_scan = 0 and drop them.
  • The planner may ignore them. Too many matching rows, or stale statistics (ANALYZE has not run), and the sequential scan wins.
  • Function-wrapped columns cannot use a plain index:
CREATE INDEX CONCURRENTLY idx_orders_user ON orders (user_id);

CONCURRENTLY avoids a lock that blocks writes, at the cost of a longer build and the possibility of leaving an INVALID index if it fails — which you DROP INDEX and retry. It cannot run inside a transaction block.

EXPLAIN ANALYZE
SELECT b.title FROM books b
WHERE b.author_id = 42
ORDER BY b.published_on DESC
LIMIT 10;
Limit (cost=0.43..8.71 rows=10 width=32) (actual time=0.031..0.052 rows=10 loops=1)
-> Index Scan using idx_books_author_date on books b
(cost=0.43..830.12 rows=1000 width=32) (actual time=0.029..0.047 rows=10 loops=1)
Index Cond: (author_id = 42)
Signal Meaning
Seq Scan on a large table with a selective WHERE Missing or unusable index
rows=1000 estimated, rows=10 actual Stale statistics; run ANALYZE
Sort over a large input No index matching the ORDER BY
Nested Loop with high loops= Repeated inner scans; likely a missing index
Rows Removed by Filter: 900000 Index used, but not selective enough for the filter
Bitmap Heap Scan + Recheck Cond Planner chose a bitmap path; usually fine

EXPLAIN alone shows estimates; EXPLAIN ANALYZE executes and shows reality.

  1. Why does WHERE published_on > ? not use an index on (author_id, published_on)?
  2. Which column goes first in a composite index, and why?
  3. What is an index-only scan, and what does it require?
  4. Why would the planner ignore a perfectly good index?
  5. When is a partial index better than a full one?
  • Indexing every column “for safety”. Write amplification and bloat.
  • Index on (a, b) for a query filtering only on b. Unusable.
  • lower(email) = ? against an index on email. Needs an expression index.
  • Concluding from stale statistics. Run ANALYZE first.
  • Forgetting the foreign key index. Every *_id used in joins needs one.
  • CREATE INDEX on a large live table without CONCURRENTLY. Blocks writes for the duration.