← Back to Backend, page 2

backend-0026 · Medium mid

How do composite (multi-column) indexes work, why does column order matter, and what is the leftmost prefix rule?

A composite index sorts rows by the first column, then by the second within equal first values, and so on. It can serve conditions on the leading columns (the leftmost prefix) efficiently: (a), (a, b) and (a, b, c) filters, but a filter on b alone cannot use the sorted order well. Put equality columns first, then the column used for range or sorting, and order them by how the queries filter. The right order can also remove a sort step for ORDER BY ... LIMIT.

Full answer

How it is stored

  • Index (customer_id, status) is like a phone book sorted by last name, then first name. Finding all rows for one customer is fast. Finding all rows for one status needs a scan of the whole book.

Rules of thumb

  • Leftmost prefix: the index helps queries that filter on customer_id, or on customer_id and status. For status alone PostgreSQL 17 (no skip scan) can only read the whole index and filter, which is slow or is replaced by a sequential scan.
  • Put equality conditions first, then range or ORDER BY columns. After a range condition, later columns cannot narrow the search.
  • Put the most commonly filtered column first, unless a different order serves more queries. A single composite index can replace a single column index on its first column.
  • For ORDER BY created_at DESC LIMIT 5 per customer, index (customer_id, created_at) lets the database read the newest rows directly, without sorting.
  • Selectivity matters, but the query shape matters more. A very selective column in second position does not help queries that skip the first column.

Always verify with EXPLAIN on realistic data. The planner may still choose a sequential scan when it expects to read much of the table.

sql
SET client_min_messages = warning;
DROP TABLE IF EXISTS idx_orders;
CREATE TABLE idx_orders (id serial PRIMARY KEY, customer_id int NOT NULL, status text NOT NULL, created_at timestamptz NOT NULL, total numeric(10,2) NOT NULL);
INSERT INTO idx_orders (customer_id, status, created_at, total)
SELECT (g % 2000) + 1,
       CASE WHEN g % 200 = 0 THEN 'pending' WHEN g % 3 = 0 THEN 'shipped' ELSE 'paid' END,
       timestamptz '2026-01-01' + (g || ' minutes')::interval,
       (g % 500) + 10
FROM generate_series(1, 100000) g;

CREATE INDEX idx_orders_cust_status ON idx_orders (customer_id, status);
ANALYZE idx_orders;

\echo 1. both columns of the index
EXPLAIN (COSTS OFF) SELECT * FROM idx_orders WHERE customer_id = 5 AND status = 'paid';

\echo 2. only the leading column
EXPLAIN (COSTS OFF) SELECT * FROM idx_orders WHERE customer_id = 5;

\echo 3. only the second column: the whole index is read (look at the buffers)
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF) SELECT * FROM idx_orders WHERE status = 'pending';

CREATE INDEX idx_orders_status_cust ON idx_orders (status, customer_id);
ANALYZE idx_orders;
\echo 4. the same query when an index starts with status: far fewer buffers
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF) SELECT * FROM idx_orders WHERE status = 'pending';

\echo 5. newest orders of one customer, index (customer_id, status): a Sort is needed
EXPLAIN (COSTS OFF) SELECT * FROM idx_orders WHERE customer_id = 5 ORDER BY created_at DESC LIMIT 3;

CREATE INDEX idx_orders_cust_created ON idx_orders (customer_id, created_at);
ANALYZE idx_orders;
\echo 6. with index (customer_id, created_at): no Sort
EXPLAIN (COSTS OFF) SELECT * FROM idx_orders WHERE customer_id = 5 ORDER BY created_at DESC LIMIT 3;

DROP TABLE idx_orders;

Run with psql on PostgreSQL 17 with 100,000 generated orders. Plans can change with data size and settings, so read the shapes (Index Cond, a Sort node) and compare the Buffers lines of cases 3 and 4. The exact buffer counts and the hit or read split can differ on another machine. Save it as app.sql and run it with psql -f app.sql. Output (PostgreSQL 17 via psql, run once): 1. both columns of the index QUERY PLAN --------------------------------------------------------------------- Bitmap Heap Scan on idx_orders Recheck Cond: ((customer_id = 5) AND (status = 'paid'::text)) -> Bitmap Index Scan on idx_orders_cust_status Index Cond: ((customer_id = 5) AND (status = 'paid'::text)) (4 rows) 2. only the leading column QUERY PLAN --------------------------------------------------- Bitmap Heap Scan on idx_orders Recheck Cond: (customer_id = 5) -> Bitmap Index Scan on idx_orders_cust_status Index Cond: (customer_id = 5) (4 rows) 3. only the second column: the whole index is read (look at the buffers) QUERY PLAN ----------------------------------------------------------------------------- Bitmap Heap Scan on idx_orders (actual rows=500 loops=1) Recheck Cond: (status = 'pending'::text) Heap Blocks: exact=500 Buffers: shared hit=500 read=99 -> Bitmap Index Scan on idx_orders_cust_status (actual rows=500 loops=1) Index Cond: (status = 'pending'::text) Buffers: shared read=99 (7 rows) 4. the same query when an index starts with status: far fewer buffers QUERY PLAN ----------------------------------------------------------------------------- Bitmap Heap Scan on idx_orders (actual rows=500 loops=1) Recheck Cond: (status = 'pending'::text) Heap Blocks: exact=500 Buffers: shared hit=500 read=2 -> Bitmap Index Scan on idx_orders_status_cust (actual rows=500 loops=1) Index Cond: (status = 'pending'::text) Buffers: shared read=2 Planning: Buffers: shared hit=21 read=1 (9 rows) 5. newest orders of one customer, index (customer_id, status): a Sort is needed QUERY PLAN --------------------------------------------------------------- Limit -> Sort Sort Key: created_at DESC -> Bitmap Heap Scan on idx_orders Recheck Cond: (customer_id = 5) -> Bitmap Index Scan on idx_orders_cust_status Index Cond: (customer_id = 5) (7 rows) 6. with index (customer_id, created_at): no Sort QUERY PLAN ----------------------------------------------------------------------- Limit -> Index Scan Backward using idx_orders_cust_created on idx_orders Index Cond: (customer_id = 5) (3 rows)

Key points

  • A composite index is sorted by the first column, then the next.
  • Leftmost prefix queries can use it; others usually cannot.
  • Equality columns first, then range or sort columns.
  • The right order removes a Sort step for ORDER BY with LIMIT.
  • Check the plan on realistic data.

Common mistakes

  • Building one index per column and hoping the planner combines them well.
  • Putting a range column before equality columns.
  • Leaving duplicate indexes (a and a,b).
  • Never checking the plan.
  • Reordering columns in an existing index without checking all queries.

Follow-ups

  • What is an index skip scan?
  • How would you index WHERE a = ? AND b > ? ORDER BY c?
  • How do you find redundant indexes?

Tips

  • Use the phone book analogy.
  • State equality first, range next.
  • Mention ORDER BY with LIMIT.