Video in progress
If an index speeds up lookups, why not put an index on every column?
Every index has a cost: it is updated on every INSERT, UPDATE and DELETE, takes up disk space, and competes with the table for the in-memory cache. An index that is never used only slows down writes.
📖 Answer
If orders has 8 indexes, a single INSERT actually writes to 9 structures. On write-heavy tables (logs, events, payments) you feel that right away.
There is another hidden cost: in PostgreSQL, when an indexed column changes, a HOT update can't happen and the table bloats faster. So an unneeded index makes UPDATEs more expensive too.
In practice I do this:
- add indexes based on real queries, whatever shows up most in
WHERE,JOINandORDER BY; - check from time to time for unused ones:
SELECT relname, indexrelname, idx_scan, pg_size_pretty(pg_relation_size(indexrelid))
FROM pg_stat_user_indexes
WHERE idx_scan = 0
ORDER BY pg_relation_size(indexrelid) DESC;
Indexes with idx_scan = 0 that take up gigabytes turn up in many projects. Before dropping one, check that it isn't used on the replicas either, since statistics are kept separately on each server.
Sign up to mark studied questions and save your progress.