PostgreSQL indexing, practically
Which index to add, why the planner ignores the one you added, and when an index makes things worse.
Adding an index is easy. Adding the right one, and knowing when not to, is the part that takes reading query plans.
Start from the query, not the column
The common mistake is indexing columns that "look important". Indexes exist for queries. Open the slow query, look at what it filters on, sorts by and joins on, and build for that.
explain (analyze, buffers)
select id, status, placed_at
from orders
where user_id = 42
order by placed_at desc
limit 20;Seq Scan on orders in that plan means every row is being read to find twenty. On a
table of five million orders that is your whole problem.
Column order in a composite index
create index on orders (user_id, placed_at desc);This one index handles the filter and the sort. The order of the columns is not a detail:
- Equality columns first (
user_id) - Range or sort columns after (
placed_at)
An index on (placed_at, user_id) cannot help that query nearly as much, because the
first column is not what you filter by.
Partial indexes
If you only ever query one slice of a table, only index that slice.
create index on orders (placed_at)
where status = 'pending';Pending orders might be 0.5% of the table. This index is tiny, stays in memory, and updates cost almost nothing on the other 99.5% of writes.
I use these a lot for job queues and status polling.
Covering indexes
create index on orders (user_id, placed_at desc) include (status, total_cents);If every column the query needs is in the index, Postgres can answer from the index alone, an index only scan with no trip to the heap. Worth it for a hot query. Not worth it for everything, because you are duplicating data and slowing writes.
Why your index is not being used
Four reasons I run into:
- A function on the column.
where lower(email) = $1cannot use an index onemail. Index the expression instead:create index on users (lower(email)). - Type mismatch. Comparing a
bigintcolumn to a text parameter forces a cast and kills the index. - Low selectivity. If
status = 'active'matches 80% of rows, a sequential scan genuinely is faster. The planner is right and you are wrong. - Stale statistics. After a big import, run
analyze. The planner is making decisions from numbers that are no longer true.
When an index makes things worse
Every index is extra work on insert, update and delete, and extra pages to keep warm. A table with twelve indexes has a slow write path, and usually four of those indexes are never used.
select relname, indexrelname, idx_scan
from pg_stat_user_indexes
where idx_scan = 0
order by relname;Anything with idx_scan = 0 after a few weeks of real traffic is paying rent and doing
nothing. Drop it.
Pagination
offset 10000 reads and throws away ten thousand rows. It gets slower the further the
user scrolls, which is exactly backwards from what they expect.
-- keyset pagination
select id, placed_at
from orders
where user_id = 42
and placed_at < $last_seen_placed_at
order by placed_at desc
limit 20;Same cost on page 500 as on page 1. It cannot jump to an arbitrary page number, which for a mobile app's infinite scroll is not a loss at all.
The habit that matters
Run explain (analyze, buffers) before adding an index, and again after. If the plan
did not change, the index was a guess. Two minutes of reading a plan beats an afternoon
of adding indexes and hoping.