Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

Part 17 / Topic 2 of 8

Composite indexes: column order decides

One index over several columns is sorted by the first column, then the second within it — a phone book: last name, then first name. You can find every Sharma, or Sharma, Priya — but "everyone named Priya" means reading the whole book.

CREATE INDEX idx_users_status_joined ON big_users (status, joined_on);
EXPLAIN (COSTS OFF)
SELECT * FROM big_users WHERE status = 'pending' AND joined_on > DATE '2024-11-01';
EXPLAIN (COSTS OFF)
SELECT * FROM big_users WHERE joined_on > DATE '2024-12-25';
CREATE INDEX
                                      QUERY PLAN                                       
---------------------------------------------------------------------------------------
 Bitmap Heap Scan on big_users
   Recheck Cond: ((status = 'pending'::text) AND (joined_on > '2024-11-01'::date))
   ->  Bitmap Index Scan on idx_users_status_joined
         Index Cond: ((status = 'pending'::text) AND (joined_on > '2024-11-01'::date))
(4 rows)

                      QUERY PLAN                      
------------------------------------------------------
 Bitmap Heap Scan on big_users
   Recheck Cond: (joined_on > '2024-12-25'::date)
   ->  Bitmap Index Scan on idx_users_status_joined
         Index Cond: (joined_on > '2024-12-25'::date)
(4 rows)

First query: descends straight to the pending run, range-scans dates within it. Second: can't use the index's order at all (no status to descend by) — the planner scans the table instead. The design rule that falls out: equality columns first, range columns after. (status, joined_on) serves status = X AND joined_on > Y perfectly; (joined_on, status) would descend by date and then crawl. Corollary: an index on (a, b) makes a separate index on (a) almost always redundant — leading-column queries use the composite.

🧪 Quick quiz — answer from memory, then check.

  1. An index on (customer_id, order_date) — which queries does it serve well?
  2. Equality + range in one WHERE: which column leads?
Show the answers
  1. customer_id = X alone, and customer_id = X AND order_date <op> Y — anything anchored on the leading column.
  2. The equality column — descend to its run, then range within it.

Done here? The practice set for Part 17 — 5 exercises with solutions — is on the part page.

Search the guide