All writing
2 min read

Postgres indexes that earn their keep

A short checklist for choosing indexes from query plans and workload shape instead of adding one for every column.

  • PostgreSQL
  • performance

An index is a maintenance contract. Every insert, update, and delete pays for it. Before adding one, answer two questions: which query needs it, and what does the plan currently do?

Start with the plan

EXPLAIN (ANALYZE, BUFFERS) is the source of truth. A sequential scan is not automatically a problem. On a small table, or a query that reads most rows, it is often the correct choice.

Look for:

  • Rows removed by a filter after the scan.
  • A large gap between estimated and actual rows.
  • Repeated heap fetches from an index scan.
  • Sort operations that spill to disk.

Match the index to the access path

A composite index is ordered. (tenant_id, created_at) helps a query that filters by tenant and sorts by time. (created_at, tenant_id) does not help the same query as directly.

For a query like:

select id, status, created_at
from orders
where tenant_id = $1
  and status = 'open'
order by created_at desc
limit 50;

A useful starting point is (tenant_id, status, created_at desc). The equality columns come first, then the sort column. Include columns only after measuring the heap fetch cost.

Prefer fewer, sharper indexes

  • Drop indexes that no query uses.
  • Avoid duplicate prefixes: (a) is redundant if (a, b) exists.
  • Use partial indexes for skewed states, such as where status = 'open'.
  • Recheck write-heavy tables: an index that speeds one report can slow every checkout.

Verify with production-shaped data

Planner behaviour depends on statistics and data distribution. A test database with ten rows proves nothing. Run the plan against realistic volume, then re-run after the index is created.

The checklist

  1. Capture the query and its plan.
  2. Identify the expensive step.
  3. Propose the smallest index that changes that step.
  4. Measure read improvement and write cost.
  5. Remove the index if it does not earn its keep.

The goal is not more indexes. The goal is a workload that stays predictable as the table grows.