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

Part 17 / Topic 3 of 8

Partial indexes

Only 5% of our users are pending, and the hot query is "pending users". Why index the 95% nobody searches? A partial index carries a WHERE:

CREATE INDEX idx_users_pending ON big_users (joined_on) WHERE status = 'pending';
SELECT pg_size_pretty(pg_relation_size('idx_users_status_joined')) AS full_index,
       pg_size_pretty(pg_relation_size('idx_users_pending'))       AS partial_index;
EXPLAIN (COSTS OFF)
SELECT * FROM big_users WHERE status = 'pending' AND joined_on > DATE '2024-11-01';
CREATE INDEX
 full_index | partial_index 
------------+---------------
 736 kB     | 56 kB
(1 row)

                                      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)

A twentieth of the size, and the planner picks it whenever the query's WHERE implies the index's WHERE. Partial indexes are also how you express conditional uniqueness — "one active subscription per user": CREATE UNIQUE INDEX ... (user_id) WHERE status = 'active'. Smaller, hotter-in-cache, cheaper to maintain — the professional's favourite trim.

🧪 Quick quiz — answer from memory, then check.

  1. When can the planner use a partial index?
  2. Spell "at most one active session per user" as an index.
Show the answers
  1. When the query's conditions provably imply the index's WHERE clause.
  2. CREATE UNIQUE INDEX ... ON sessions (user_id) WHERE status = 'active';

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

Search the guide