HAMZA KAREEM / CONCEPTS hamzawi.dev

Lesson 1182 min read

Composite Index Column Order

(a,b) and (b,a) Are Not the Same Index

Databasesdatabases / indexing & query performance

The setup

Table events, 50M rows. The query every dashboard runs:

WHERE tenant_id = 42
  AND created_at > now() - interval '7 days'
ORDER BY created_at DESC
LIMIT 50

Two candidate indexes. Same two columns. Different order.

A: (tenant_id, created_at)
B: (created_at, tenant_id)

Side by side

A (tenant,time)      B (time,tenant)

Rows actually seeked 1.2k (just tenant 42) 9M (whole week, all tenants)

Second column does seeks filters only

Sort needed for ORDER BY no yes — Sort node

Typical timing ~0.8 ms ~420 ms

Same columns. ~500x. Order is the whole lesson.

The rule

A B-tree is a phone book sorted by (last, first). You can only seek on a leftmost prefix.

  • Equality columns first
  • ONE range/inequality column last
  • After a range column, remaining columns stop being seekable — they degrade to filters

A: seek straight to tenant 42, walk a contiguous slice of created_at, stop at 50 rows.

B: seek the time range, then scan 9M rows checking tenant_id one by one.

The ORDER BY gotcha

(tenant_id, created_at) serves "ORDER BY created_at DESC" fine — engines walk B-trees backwards.

But MIXED directions break it: "ORDER BY tenant_id ASC, created_at DESC" needs the index declared as (tenant_id, created_at DESC). Otherwise you eat a Sort even though the columns "match".

How to check in 10 seconds

EXPLAIN (ANALYZE, BUFFERS) your query and read where each column landed:

good:
  Index Cond: (tenant_id = 42 AND created_at > ...)

bad:
  Index Cond: (created_at > ...)
  Filter: (tenant_id = 42)
  Rows Removed by Filter: 8998800     <- smoking gun

"Rows Removed by Filter" on an index scan ≈ your column order is wrong.

Three traps practitioners hit

  1. Don't keep an index on (tenant_id) once you have (tenant_id, created_at) — the prefix already covers it. Redundant indexes tax every INSERT and bloat your WAL.
  2. "Most selective column first" is folklore. Equality columns go first; selectivity only breaks ties among equals.
  3. Index Skip Scan (MySQL 8.0, PG 18) can partly rescue a wrong leading column, but only when it has very few distinct values. Don't design around it.

Your exercise

You have idx(status, created_at). status has 4 distinct values. Query:

WHERE created_at > $1
  AND status IN ('open','pending')
ORDER BY created_at
LIMIT 100

Three questions:

a) Is the index usable at all here, given status is an IN-list and not a single equality?

b) Which column seeks and which filters?

c) Does the plan still need a Sort node — and why does an IN-list on the leading column change the answer versus status = 'open'?

Run EXPLAIN ANALYZE both ways (IN-list vs single value) and look for the Sort.