Sub topic 16
A Practical Approach to Choosing Indexes
Assume you know basic SELECT, WHERE, ORDER BY, and JOIN syntax. You should also understand tables, rows, primary keys, and the difference between linear and logarithmic work.
An index is useful when it reduces the rows the database must inspect. Choosing indexes is therefore a workload decision, not a rule to index every column.
Start with the workload
Begin with the queries that matter most:
- Queries run often.
- Queries that read many rows or respond slowly.
- Queries used on important user-facing paths.
- Queries that filter, join, or sort by the same columns.
Record each query's filters, joins, sort order, returned columns, and approximate frequency. Then check its actual plan with EXPLAIN, preferably with realistic data.
EXPLAIN
SELECT id, total_cents
FROM orders
WHERE customer_id = 42
AND status = 'open'
ORDER BY created_at DESC
LIMIT 20;A good index should match the query's access pattern. For this query, an index beginning with customer_id and status, followed by created_at, may help:
CREATE INDEX orders_customer_status_created_idx
ON orders (customer_id, status, created_at DESC);Column order matters. Put columns used for equality conditions before columns used for ranges or ordering when that matches the workload. Test alternatives rather than relying on a slogan. A different order may be better for a different query.
Check the trade-offs
Use this decision table as a starting point.
| Question | Possible choice | Reason |
|---|---|---|
| Does a query filter by a selective column? | Single-column index | Finds a small subset efficiently |
| Does it filter by several columns together? | Composite index | Supports the combined access pattern |
| Does it return a few extra columns? | Covering index | May avoid table reads |
| Does it query a stable subset? | Partial index | Keeps the index smaller |
| Does it filter on a repeated expression? | Expression index | Indexes the value the query searches |
A column is selective when a condition matches a small fraction of rows. An index on a boolean column may help when only a small fraction of rows are true, but may not help when half the table matches.
Every index has a cost. Inserts, updates, and deletes must maintain it. Indexes also consume storage and can slow bulk loading. Avoid near-duplicate indexes unless separate queries justify them.
A repeatable design loop
After deployment, monitor query latency, index usage, write rate, and storage. An unused index is a candidate for removal, but verify that reporting, batch, or infrequent administrative queries do not need it.
Exercise
Exercise
A query filters on customerid and createdat, then returns total_cents. Which index would you test first, and why?
Show answer
Test an index such as (customerid, createdat) and consider INCLUDE (totalcents). customerid supports the initial lookup, createdat supports the range, and totalcents may allow an index-only scan.