← Building blocks

Index selective columns first

Latency & performancesenior

An index on status with three values barely narrows the rows, so the planner ignores it.

Say it like this

The index has to be selective, so I lead the composite index with the column that narrows rows the most and put the sort key second, which lets the planner seek straight to the rows and return them in order without a sort.

Basic solution

Put the most selective column (many distinct values) first in a composite index, and match the index order to the WHERE and ORDER BY. Use partial indexes for the rare value you actually query.

composite index column orderpartial indexescovering indexescardinality stats

Partial composite index for the retry queue

The partial index holds only failed rows, sorted by channel then time, so the worker seeks to sms and reads 1,000 entries in order. The full table is never scanned.

How it works

  1. Measure selectivity for each candidate column: the number of distinct values divided by the number of rows. On a 250M row table, user_id with 50M distinct values is highly selective (a lookup returns about 5 rows); status with 3 values is not (a lookup returns about 80M rows).
  2. Order the columns in a composite index with the equality predicates first, most selective first, and the range or sort column last. The index is a sorted structure, so the planner can only seek on a prefix of the column list.
  3. Check the leading-column rule: an index on (a, b) can answer WHERE a = ?, WHERE a = ? AND b = ?, and WHERE a = ? ORDER BY b, because all of those start with a. It cannot answer WHERE b = ? on its own, because the index is not sorted by b.
  4. For a rare value you query constantly (status = failed, 0.1 percent of rows), build a partial index with WHERE status = failed. It contains only those rows, so it is tiny and every entry is a match.
  5. Add the columns the query returns as INCLUDE columns when you want a covering index: the database then answers from the index alone and never fetches the table rows, at the cost of a wider index.
  6. Confirm with EXPLAIN that the planner uses the new index and that the Sort node has disappeared, then watch write latency, because every index adds work to every insert.

Why low-selectivity indexes get ignored

  • If 40 percent of rows match, following the index means jumping to random table pages for 100 million rows, which costs more than reading the whole table sequentially. The planner is right to skip the index.

Worked example

Delivery rows in the notification system

  • Table delivery: 750 million rows, 300 bytes each. Columns include notification_id, channel (3 values), provider (4 values), status (5 values), created_at.
  • Query A, the retry worker: WHERE status = failed AND channel = sms ORDER BY created_at LIMIT 1000. Failed is 0.5 percent of rows, sms is 10 percent.
  • Query B, the status page: WHERE notification_id = ? (one to three rows).
  • Wrong index: (channel, status, created_at). Leading column channel keeps 75 million rows; status narrows to 375,000; the index is 750M entries wide and the write cost is paid on every delivery.
  • Better: a partial index ON delivery (channel, created_at) WHERE status = failed. It holds 3.75 million entries (0.5 percent), the seek on channel narrows to 375,000 in order, and LIMIT 1000 stops after reading 1,000 entries. Size: roughly 3.75M times 40 bytes, about 150 MB instead of 30 GB.
  • Query B gets its own index on notification_id: 50M distinct values across 750M rows means 15 rows per key, a single index seek.
  • Write cost: each delivery insert now updates two small indexes instead of one huge one; at 2,900 inserts per second the partial index is touched only for the 15 per second that fail.

Variants and when each wins

Composite index, equality columns first

  • One index over several columns, ordered by selectivity among the equality predicates and ending with the range or sort column. It is the default, and one such index serves every query that filters on a prefix of its columns.

Partial index

  • An index that contains only the rows matching a predicate. It wins for queue-like queries on a rare status, and the planner only uses it when the query's WHERE clause provably implies the index predicate.

Covering index with INCLUDE

  • An index that also stores columns the query returns but does not filter on. It wins for hot read paths returning a few columns, because the table is never touched; the cost is a bigger index.

Expression index

  • An index over a computed value such as lower(email) or a JSON field. It wins when the query must filter on a function of the column, which a plain index cannot serve.

Recommendation: start with one composite index per hot query shape, equality columns first; reach for partial indexes on rare-status queues and covering indexes on the busiest reads.

Failure modes

Index exists but is unused

  • You notice EXPLAIN shows a Seq Scan despite the index. It happens because the query does not filter on the index's leading column, wraps the column in a function, or matches so many rows that a scan is cheaper. Fix it by reordering the index columns, using an expression index, or accepting the scan for a query that genuinely needs most rows.

Too many indexes

  • You notice insert latency climbing and the table's indexes taking more space than its data. It happens because an index was added per query and many of them overlap. Fix it by merging indexes that share a prefix, dropping the ones pg_stat_user_indexes shows are never used, and preferring partial indexes where a predicate is fixed.

Partial index predicate drift

  • You notice the queue query got slow after a code change. It happens because the query now filters on status IN (failed, expired), and the partial index built for status = failed no longer applies. Fix it by keeping the index predicate and the query in the same place in code, and running EXPLAIN against the query in CI.

Skewed values

  • You notice a selective column is fast for most values but slow for one. It happens because one tenant owns 30 percent of the rows, so for that key the index returns tens of millions of entries. Fix it with extended statistics so the planner knows about the skew, and a different access path for that one whale tenant.

Range column first

  • You notice WHERE user_id = ? AND created_at > ? uses the index but reads far more entries than it returns. It happens because created_at was placed first, so the seek lands on a date and then has to filter every user from there on. Fix it by putting the equality column first and the range column last.

Interviewer follow-ups

Answer out loud before you open each one.

Why does column order in a composite index matter?

The index is sorted by the first column, then the second within it. A seek can only use a prefix, so a predicate on the second column alone has to scan the whole index. Put the columns you always filter by equality first, most selective first, and the range or sort column last.

When is a partial index the wrong choice?

When the predicate changes often, when the matching fraction is large enough that a full index would do, or when many queries need the same columns with different predicates. The planner only uses a partial index if it can prove the query predicate implies the index predicate.

How do you decide whether an index is worth its write cost?

Compare reads served against inserts paid. An index used 5,000 times per second and updated 50 times per second pays for itself; one used once a day on a table written 3,000 times per second does not, unless that daily query is the one that matters. pg_stat_user_indexes gives the usage counts.

What does a covering index buy, and what does it cost?

It lets the query return from the index without visiting the table, removing random page reads and often halving latency on hot reads. The cost is a wider index that grows with every included column and slows writes, and in Postgres the visibility map must be fresh for index-only scans to skip the heap.

Connections

Built on
B-tree · Bitmap index
Pairs with
Index the columns you filter on · Read the query plan · Page results with a cursor · Know your write amplification

The same parts on other clouds

The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.

AWSUsed here asGoogle CloudMicrosoft AzureOpen source and others
Amazon EC2 Auto ScalingRetry worker, Status APICompute Engine managed instance groupsVirtual Machine Scale SetsKubernetes Deployment with a HorizontalPodAutoscaler, Nomad