Chapter 04

Indexes

An index is a trade: faster reads, slower writes, more disk. This chapter is about making that trade deliberately instead of adding one index per complaint.

⏱ 18 min readLevel: intermediateCore chapter
Comparison of B-tree, GIN, GiST, BRIN, Hash and SP-GiST index types with the query shapes each serves, plus index modifiers
Match the index structure to the query shape — then to the modifiers, which matter more.

Column order in a composite index

the left-prefix rule
CREATE INDEX idx_order_cust_date
  ON customer_order (customer_id, placed_at DESC);

-- USES the index
WHERE customer_id = 42
WHERE customer_id = 42 AND placed_at > now() - interval '30 days'
WHERE customer_id = 42 ORDER BY placed_at DESC

-- CANNOT use it efficiently (no leading column)
WHERE placed_at > now() - interval '30 days'
The ordering rule

Equality columns first, then the range or sort column. A query filtering status = 'PAID' and ordering by placed_at wants (status, placed_at) — never the reverse.

Partial indexes — the biggest easy win

index 2% of the table
-- most orders end up DELIVERED; you only ever query the open ones
CREATE INDEX idx_order_open
  ON customer_order (placed_at)
  WHERE status IN ('PLACED','PAID');

-- unpublished outbox rows: tiny index over a huge table
CREATE INDEX idx_outbox_pending
  ON outbox_event (event_id)
  WHERE published_at IS NULL;

-- enforce a rule conditionally: one active subscription per customer
CREATE UNIQUE INDEX uq_active_subscription
  ON subscription (customer_id)
  WHERE status = 'ACTIVE';

The predicate must match the query's WHERE closely enough for the planner to prove the index is applicable.

Covering indexes and index-only scans

INCLUDE avoids touching the table
CREATE INDEX idx_order_lookup
  ON customer_order (customer_id, placed_at DESC)
  INCLUDE (reference, total_amount, status);

-- this query is now answered entirely from the index
SELECT reference, total_amount, status
FROM   customer_order
WHERE  customer_id = 42
ORDER  BY placed_at DESC
LIMIT  20;
-- EXPLAIN shows: Index Only Scan using idx_order_lookup
Index-only scans need the visibility map

PostgreSQL must still confirm each row is visible to your snapshot. It skips that check only for pages marked all-visible by vacuum. If a plan shows a high Heap Fetches count, the table needs vacuuming — see chapter 6.

Expression indexes

index the expression the query uses
-- WHERE lower(email) = ? cannot use an index on email
CREATE INDEX idx_customer_email_lower ON customer (lower(email));

-- or avoid the problem entirely with citext (chapter 2)

-- date truncation for reporting
CREATE INDEX idx_order_month
  ON customer_order (date_trunc('month', placed_at));

-- a JSONB key you filter on constantly
CREATE INDEX idx_order_channel
  ON customer_order ((metadata ->> 'channel'));

The expression in the index must match the query textually. lower(email) is used; upper(email) is not.

GIN for JSONB, arrays and full text

two GIN flavours for JSONB
-- default: supports @>, ?, ?&, ?| — larger index
CREATE INDEX idx_meta_gin ON customer_order USING gin (metadata);

-- jsonb_path_ops: only @>, but ~3x smaller and faster
CREATE INDEX idx_meta_path ON customer_order USING gin (metadata jsonb_path_ops);

SELECT * FROM customer_order WHERE metadata @> '{"channel":"mobile"}';
IndexReadWrite costSize
B-treeFastLowModerate
GINVery fast for containmentHigh — indexes every elementLarge
GiSTGood for overlap/nearestModerateModerate
BRINOnly if physically orderedNegligibleTiny

What indexes cost

  • Every write pays. An INSERT updates the table and every index on it. Eight indexes means nine writes.
  • Disk and cache. Indexes compete with table data for shared_buffers.
  • Vacuum time. More indexes means slower cleanup.
  • Planning time. Dozens of indexes on one table measurably slows planning.
find indexes nobody uses
SELECT s.relname                          AS table_name,
       s.indexrelname                     AS index_name,
       s.idx_scan                         AS times_used,
       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 < 50
  AND  NOT i.indisunique
ORDER  BY pg_relation_size(s.indexrelid) DESC;
find missing ones
SELECT relname,
       seq_scan,
       seq_tup_read,
       idx_scan,
       seq_tup_read / nullif(seq_scan, 0) AS avg_rows_per_seq_scan
FROM   pg_stat_user_tables
WHERE  seq_scan > idx_scan
  AND  seq_tup_read > 100000
ORDER  BY seq_tup_read DESC;

Creating indexes safely

always CONCURRENTLY in production
-- blocks all writes for the duration — never do this on a live table
CREATE INDEX idx_a ON big_table (col);

-- does not block writes; takes longer and cannot run inside a transaction
CREATE INDEX CONCURRENTLY idx_a ON big_table (col);

-- if it fails it leaves an INVALID index behind — check and clean up
SELECT indexrelid::regclass FROM pg_index WHERE NOT indisvalid;
DROP INDEX CONCURRENTLY idx_a;

Queries filter status = 'PLACED' and sort by placed_at, and only 2% of rows are PLACED. Best index?

A partial index stores only the 2% of rows you query, so it is far smaller, stays in cache, and costs nothing to maintain for the other 98% of writes. The composite index with placed_at first also violates the left-prefix rule for the equality filter.