Sub topic 16
A practical approach to choosing indexes
This chapter assumes you know basic SQL, can read an EXPLAIN plan, and understand B-tree lookups, composite indexes with the leftmost-prefix rule, covering indexes, and the write cost of maintaining indexes. It pulls those pieces into a repeatable method for deciding which indexes to create. The examples use PostgreSQL syntax.
Start from the workload, not the schema
An index exists to serve a query. Choosing indexes by looking at columns ("this one looks important") produces indexes nobody uses. Choosing by workload produces a small set that earns its cost.
Gather three facts first:
- Which queries run, and how often. Use a slow-query log or
pg_stat_statementsif you have it. A query that runs 50 times a second matters more than a report that runs once a night. - How slow each one is, and how slow it is allowed to be. A 300 ms query behind a user-facing page is a problem. The same query in a batch job may not be.
- The write rate on the tables involved. Every index you add slows
INSERT,UPDATE, andDELETEon that table.
Then work through the queries from most expensive (frequency times duration) downward. Do not try to index everything.
A worked workload
Suppose an orders table with about 50 million rows serves these queries:
| Query | Shape | Frequency |
|---|---|---|
| A | Fetch one order by `id` | Very high |
| B | A customer's recent orders, newest first, 20 rows | High |
| C | Count of open orders created in the last hour | Medium |
| D | Monthly revenue report across all orders | Once a day |
CREATE TABLE orders (
id bigint PRIMARY KEY,
customer_id bigint NOT NULL,
status text NOT NULL,
created_at timestamptz NOT NULL,
total_cents integer NOT NULL
);Walk through each query and ask the same questions: which predicates does it have, which rows does it return, and does an existing index already help?
Query A: already covered
The primary key creates a unique B-tree index on id. Nothing to add. Check for this before creating anything, since a duplicate index only adds write cost.
Query B: equality, then sort
SELECT * FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 20;The query has an equality predicate on customer_id and an ordering on created_at. A composite index with the equality column first and the sort column second lets the database seek to the customer and read entries in order, then stop after 20. It does no separate sort.
CREATE INDEX orders_customer_created_idx
ON orders (customer_id, created_at);A B-tree can be scanned backward, so the ascending index serves DESC ordering. This one index also serves queries that filter on customer_id alone, which makes a separate (customer_id) index redundant.
Query C: a small slice of the table
SELECT count(*) FROM orders
WHERE status = 'open'
AND created_at >= now() - interval '1 hour';Most orders are not open, and the time window is narrow. A partial index keeps only the rows that matter:
CREATE INDEX orders_open_created_idx
ON orders (created_at) WHERE status = 'open';It is much smaller than a full index on created_at, and it is cheaper to maintain, because writes to non-open orders do not touch it. The query must include a condition the planner can match to status = 'open', or the index cannot be used.
Query D: leave it alone
A daily report that scans a large share of the table is a poor reason to add an index. Low selectivity means the planner will choose a sequential scan anyway. Accept the scan, run it on a replica, or precompute the result. An index here would slow every write all day to speed up one query at night.
The decision loop
For each candidate query, apply the same loop.
Rules of thumb for column order
When you design a composite index, use this order:
- Columns compared with
=come first. - Then the column used for a range (
>,<,BETWEEN) or forORDER BY. - Among several equality columns, put the one that appears in the most queries first, since that makes the index usable by more of them.
- Add
INCLUDEcolumns last, only when they let a hot query become an index-only scan.
Why the range column goes last: entries are ordered by the first column, then the second within it, and so on. Once the index hits a range condition, the columns after it are no longer in a single contiguous run, so they cannot narrow the seek.
Selectivity helps break ties, but it is not a rule that the most selective column always goes first. A column like status with few distinct values is a fine leading column if every query constrains it by equality.
Check your work with EXPLAIN
Never assume that a new index is used. Create it, then check.
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 20;Look for these signs of success:
- An
Index ScanorIndex Only Scanon the new index, with no separateSortnode. - A small number of buffers read, compared with the plan before the change.
- Actual row counts close to the estimates. A large gap suggests stale statistics, so run
ANALYZE ordersand check again.
On a small development table the planner may still pick a sequential scan, because reading a few pages is cheaper than an index. Test on data that resembles production in size and distribution. To see whether an index is possible, you can run SET enable_seqscan = off; in a session, but treat that as a diagnostic only and never as a fix.
Weigh the cost
Each index you keep has a price:
| Cost | Effect |
|---|---|
| Write amplification | Each insert adds an entry to every index. Updates to indexed columns do too. |
| Storage | Indexes on large tables can be a large fraction of the table's size. |
| Memory | Indexes compete with table data for cache. |
| Maintenance | More indexes mean more vacuuming, more bloat, and slower bulk loads. |
A practical budget: be able to say, for every index, which query it serves. If you cannot, it is a candidate for removal.
Prune indexes you do not need
Indexes accumulate. Review them periodically.
SELECT relname AS table_name,
indexrelname AS index_name,
idx_scan,
pg_size_pretty(pg_relation_size(indexrelid)) AS size
FROM pg_stat_user_indexes
WHERE idx_scan = 0
ORDER BY pg_relation_size(indexrelid) DESC;An index with idx_scan = 0 over a long period is a removal candidate. Before dropping it, check three things:
- The statistics were not reset recently. They only count since the last reset.
- The index does not back a
UNIQUEor primary key constraint. Those enforce rules, not just speed. - It is not needed for a rare but critical query, such as a month-end job. Check that the counter covers a full business cycle.
Also look for redundant prefixes. An index on (customer_id) is redundant when (customer_id, created_at) exists, apart from a slightly smaller footprint on lookups that only use the first column.
In production, create and drop indexes without blocking writes:
CREATE INDEX CONCURRENTLY orders_customer_created_idx
ON orders (customer_id, created_at);
DROP INDEX CONCURRENTLY orders_old_idx;CREATE INDEX CONCURRENTLY takes longer and cannot run inside a transaction block. If it fails, it leaves an invalid index behind that you must drop and recreate.
Common mistakes
- Indexing every column. It multiplies write cost and rarely helps queries that combine several predicates.
- Wrong column order. An index on
(created_at, customer_id)does not serveWHERE customer_id = 42well. - Wrapping the column in a function.
WHERE date_trunc('month', created_at) = ...defeats a plain index. Rewrite it as a range, or build an expression index. - Indexing low-selectivity columns alone. A standalone index on a boolean rarely gets chosen.
- Skipping verification. An index nobody confirmed with
EXPLAINis a guess.
Summary of the method
- List the queries that matter and rank them by frequency times cost.
- For each, check whether an existing index already serves it.
- Design the smallest index that does: equality columns, then range or sort, then optional
INCLUDE. - Consider a partial or expression index when the query targets a narrow slice or a computed value.
- Create it, run
EXPLAIN (ANALYZE, BUFFERS)on realistic data, and keep it only if the plan improves. - Review unused and redundant indexes on a schedule.
Exercise
A sessions table has 200 million rows. The hottest query is SELECT * FROM sessions WHERE user_id = ? AND ended_at IS NULL ORDER BY started_at DESC LIMIT 5. Only about 0.1% of rows have ended_at IS NULL, and the table receives heavy inserts. Propose one index, justify the column order, and name one risk to check.
Show answer
Create a partial index: CREATE INDEX sessions_active_idx ON sessions (user_id, started_at) WHERE ended_at IS NULL;. user_id is an equality column so it goes first, and started_at is the sort column so it goes second, which lets the database read the newest entries first and stop after 5 rows. The WHERE clause keeps the index to the roughly 0.1% of rows that are active, so it stays small and most inserts of already-ended sessions do not touch it. Risks to check: the query must repeat ended_at IS NULL so the planner can match the index predicate, and rows that later get an ended_at value leave the index on update, which adds write work you should measure. Verify with EXPLAIN (ANALYZE, BUFFERS) on production-sized data.
Exercise
pg_stat_user_indexes shows an index orders_status_idx with idx_scan = 0 after three months. List two checks to make before you drop it.
Show answer
First, confirm the index does not enforce a unique or primary key constraint. Second, confirm the statistics cover a full business cycle and have not been reset recently, so that a rare month-end or quarter-end query is not using it. Dropping with DROP INDEX CONCURRENTLY also avoids blocking writes.