Sub topic 14
Choosing an Index Design for a Workload
Assume you know basic SELECT, WHERE, ORDER BY, and CREATE TABLE. You should also understand that an index speeds up some reads by adding an ordered data structure, but it increases storage and write work.
Index design starts with queries, not columns. Write down the important query shapes, how often they run, how many rows they usually return, and how often the table changes.
Start with the query shape
Use a multicolumn B-tree index when a query commonly filters on several columns or filters on one column and sorts by another.
CREATE INDEX orders_customer_created_idx
ON orders (customer_id, created_at DESC);
EXPLAIN
SELECT id, status, total_cents, created_at
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 20;This index places rows for each customer together and stores that customer's newest orders first. The planner may use an index scan that stops after 20 rows, avoiding a separate sort and avoiding reading older orders.
Column order matters. Put equality conditions first when possible, then range conditions or sort columns. An index on (customer_id, created_at) is useful for customer_id = 42, but usually not for a query that filters only on created_at. This is called leftmost-prefix behavior: the scan works best when the query constrains the index's leading columns.
Choose a partial index for a stable subset
A partial index contains only rows matching its predicate. It is useful when a small, frequently queried subset remains meaningful, such as pending orders or active users.
CREATE INDEX orders_pending_created_idx
ON orders (created_at)
WHERE status = 'pending';
EXPLAIN
SELECT id, created_at
FROM orders
WHERE status = 'pending'
AND created_at < now() - interval '1 hour';The query must let PostgreSQL prove that its conditions imply status = 'pending'. Keep the predicate simple and write matching queries consistently. A query for status IN ('pending', 'processing') cannot generally use an index restricted to only pending rows.
Partial indexes reduce index size and write cost for excluded rows. They are a poor fit when nearly every row belongs to the subset or when the predicate changes frequently.
Enforce conditional uniqueness
A unique partial index enforces uniqueness only for rows in its predicate.
CREATE UNIQUE INDEX users_active_email_key
ON users (email)
WHERE deleted_at IS NULL;This allows a soft-deleted user to have the same email as a new active user. Use this design when the business rule applies to a subset, not to the entire table.
Index the value the query uses
An expression index stores a computed value. The query must use the same expression.
CREATE INDEX users_lower_email_idx
ON users (lower(email));
EXPLAIN
SELECT id
FROM users
WHERE lower(email) = '[email protected]';Functions used by index expressions and predicates must be immutable. An immutable expression always returns the same result for the same inputs. PostgreSQL rejects expressions whose result can change with the session or current time. For example, use an explicit time zone when indexing a timestamp conversion.
INCLUDE columns can cover a query without changing the index's search order:
CREATE INDEX orders_customer_cover_idx
ON orders (customer_id)
INCLUDE (total_cents);PostgreSQL may then use an index-only scan, although visibility checks can still require table access.
Verify the design and its cost
Use EXPLAIN (ANALYZE, BUFFERS) on a representative query. Check whether PostgreSQL chose the intended index, how many rows it scanned, and whether estimates differ greatly from actual rows. Test with realistic data. A selective index may be ignored when a table is small or a query returns a large percentage of rows.
| Design | Best fit | Main cost |
|---|---|---|
| Multicolumn B-tree | Repeated filters and sort patterns | Larger writes and storage |
| Partial index | Small, stable queried subset | Predicate must match |
| Expression index | Filters on a computed value | Expression rules and extra maintenance |
| `INCLUDE` | Queries needing extra selected columns | Larger leaf entries |
For a busy production table, CREATE INDEX CONCURRENTLY avoids blocking ordinary writes, but it takes longer and cannot run inside a transaction block. Plan for its extra processing and monitor the build.
Exercise
You need the newest 20 orders for one customer, and most queries filter by customer before sorting by time. Which index is the best starting point?
Show answer
Create a B-tree index on (customer_id, created_at DESC), then confirm its use with EXPLAIN (ANALYZE, BUFFERS).