Sub topic 14
Choosing an Index Design for a Workload
This chapter pulls the earlier techniques together: multicolumn, partial, expression, and covering indexes. It assumes you can read basic EXPLAIN output, know why column order matters in a B-tree, and have met the orders and users tables from earlier chapters. The goal is a repeatable way to pick one design over another, and to know when to add no index at all.
Start from the queries, not the columns
Indexes serve queries. Before writing any CREATE INDEX, list the queries that matter and note four facts about each:
- Which columns it compares with equality.
- Which column it compares with a range (
<,>,BETWEEN), if any. - Whether it has an
ORDER BYorLIMIT. - Which fixed conditions it always repeats, such as
status = 'pending'ordeleted_at IS NULL.
Also note how often each query runs and how many rows it returns. A query that runs a million times a day and returns 20 rows deserves an index. A monthly report that scans most of the table usually does not.
A decision procedure
The flowchart gives a rough order of questions. It is a starting point, and you still verify the result with EXPLAIN.
A worked workload
Suppose the application runs these four queries against the running schema.
-- Q1: a customer's newest orders (every page view)
SELECT * FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 20;
-- Q2: a background job that finds stale pending orders (every minute)
SELECT id, created_at FROM orders
WHERE status = 'pending'
AND created_at < now() - interval '1 hour';
-- Q3: login lookup among active users (every request)
SELECT id FROM users
WHERE lower(email) = '[email protected]'
AND deleted_at IS NULL;
-- Q4: a customer's spending (dashboard)
SELECT customer_id, sum(total_cents)
FROM orders
WHERE customer_id = 42
GROUP BY customer_id;Q1: equality plus sort gives a multicolumn index
customer_id is compared with equality and created_at drives the sort. Equality column first, sort column second, matching the ORDER BY direction:
CREATE INDEX orders_customer_created_idx
ON orders (customer_id, created_at DESC);The planner can walk the index for customer 42 in order and stop after 20 entries. No separate sort step appears in the plan. This index also serves any query that constrains only customer_id, so a separate single-column index on customer_id is redundant. Drop it, because it only adds write cost.
Q2: a fixed condition gives a partial index
Most orders are not pending, and Q2 always asks for status = 'pending'. Index only those rows:
CREATE INDEX orders_pending_created_idx
ON orders (created_at)
WHERE status = 'pending';The index stays small because finished orders never enter it, and rows leave it when their status changes. The alternative, a full (status, created_at) index, would also work. It would be much larger and would cost writes on every status change of every order.
Q3: a computed value plus a fixed condition gives a unique partial expression index
Q3 compares lower(email) and always excludes soft-deleted users. One index can do both jobs and also enforce uniqueness among active users:
CREATE UNIQUE INDEX users_active_lower_email_key
ON users (lower(email))
WHERE deleted_at IS NULL;Two rules decide whether this index is usable. The query must contain the same expression, lower(email), not email alone. It must also contain a condition that implies the predicate, here deleted_at IS NULL. If Q3 left out the deleted_at condition, the planner could not use the index, because it cannot assume the missing rows do not matter.
Q4: a narrow read gives INCLUDE
Q4 needs only customer_id and total_cents. A covering index lets PostgreSQL answer it from the index alone:
CREATE INDEX orders_customer_cover_idx
ON orders (customer_id)
INCLUDE (total_cents);Compare this with extending the Q1 index. If total_cents is added to orders_customer_created_idx with INCLUDE, one index can serve Q1's lookups and Q4's sums. Q1 uses SELECT *, so it still has to visit the table for the other columns. The extra column only helps Q4. Whether that is worth a wider index on a busy table depends on how often Q4 runs.
CREATE INDEX orders_customer_created_cover_idx
ON orders (customer_id, created_at DESC)
INCLUDE (total_cents);Comparing the designs
| Design | Use it when | Main cost or limit |
|---|---|---|
| Multicolumn | Queries filter on several columns or filter and sort together | Helps only when the leading columns are constrained |
| Partial | Queries always repeat a condition that selects a small share of rows | Usable only when the query implies the predicate |
| Expression | Queries filter or sort on a computed value | The query must repeat the expression, and the expression must be immutable |
| Unique partial | Uniqueness applies only to a subset of rows | Same predicate matching rules as any partial index |
| INCLUDE | A hot query reads a few columns beyond the search key | Wider index, and index-only scans depend on vacuum |
These designs combine freely. Q3's index is both partial and expression-based.
Verify before and after
For each query, run EXPLAIN and look for the index name in the plan. A few habits catch most surprises:
- Run
ANALYZEon the table after loading test data. Without fresh statistics the planner guesses badly. - Test with realistic data volume. On a table of a few hundred rows, a sequential scan is often cheaper, and the planner is right to choose it.
- To check whether an index is usable at all, temporarily run
SET enable_seqscan = off;in a session and re-runEXPLAIN. If the index still does not appear, the query does not match the index definition. If it appears, the planner judged it more expensive than a scan. This is a diagnostic only, so never set it in production configuration. - Prepared statements can hide a partial index. With a generic plan, a parameter such as
status = $1has no known value at planning time, so the planner cannot prove the query impliesstatus = 'pending'. Write fixed conditions as literals in the SQL text.
Weigh the cost
Every index is updated on every insert and delete, and on updates that change an indexed column. A partial index is touched only by rows that match its predicate. Each index also takes disk space and cache memory. Review them with the statistics views:
SELECT indexrelname,
idx_scan,
pg_size_pretty(pg_relation_size(indexrelid)) AS size
FROM pg_stat_user_indexes
WHERE relname = 'orders'
ORDER BY idx_scan;An index with idx_scan of zero over a representative period is a candidate for removal. Check replicas and rare jobs such as month-end reports first. Counters reset when statistics are reset, and constraint-backing indexes must stay whatever their scan count.
Three common failures follow from ignoring cost:
- Redundant prefixes. An index on
(a)next to one on(a, b)almost never earns its keep. - Indexes for one-off queries. A report that runs weekly can usually tolerate a sequential scan.
- Low-selectivity single columns. An index on a column with two values, where each matches half the table, rarely helps. Make it a partial index on the rare value or fold it into a multicolumn index.
Building on a live table
On a table that receives writes, build indexes without blocking them:
CREATE INDEX CONCURRENTLY orders_status_created_idx
ON orders (status, created_at);The build is slower, and it cannot run inside a transaction block. If it fails, for example from a uniqueness violation, it leaves an invalid index behind. Find it with \d orders in psql, drop it with DROP INDEX CONCURRENTLY, and try again.
Exercise
Exercise
A table tickets(id, team_id, state, assignee, created_at) is queried constantly with WHERE team_id = $1 AND state = 'open' ORDER BY created_at DESC LIMIT 50. About 3 percent of tickets are open. Propose one index, justify its column order and any predicate, and say how you would check that it works.
Show answer
Create CREATE INDEX tickets_team_open_idx ON tickets (team_id, created_at DESC) WHERE state = 'open';. The team_id column is the equality column, so it comes first. created_at DESC matches the ORDER BY, so the planner can read the newest rows in index order and stop at 50 without a sort. The predicate state = 'open' is repeated in every query and selects only 3 percent of rows, so the index stays small and only open tickets cost write work. The state = 'open' condition must appear as a literal in the query, not as a parameter, or a generic plan cannot match the index. To check it, run ANALYZE tickets; and then EXPLAIN on the query. Look for tickets_team_open_idx in the plan and no separate Sort node. Afterward, watch idx_scan in pg_stat_user_indexes to confirm it keeps being used.