Difficulty: Beginner
Why shouldn't you add an index on every column of a table? What does each index cost?
Every index is a separate data structure that the database must update on every INSERT, every DELETE, and every UPDATE that touches an indexed column. Indexing every column multiplies write work, consumes disk and memory, and often does not even help reads, because the planner usually uses one well-chosen composite index rather than many single-column ones. Index the columns your real queries filter, join and sort on, and nothing more.
last_seen_at and you disable HOT for those updates.shared_buffers or the InnoDB buffer pool). Rarely used indexes evict useful pages.ANALYZE, rebuilds and schema migrations all take longer.WHERE city = 'Pune' AND status = 'PAID' ORDER BY created_at is best served by one composite index (city, status, created_at). Three single-column indexes are much weaker; the planner may combine them with a bitmap AND, but cannot use them to avoid the sort.is_active or gender rarely benefit, because the planner prefers a sequential scan when a value matches a large share of rows. A partial index like WHERE is_active is better if needed.WHERE lower(email) = ... needs an expression index, not just an index on email.pg_stat_statements, or MySQL's performance schema.EXPLAIN ANALYZE and look for sequential scans on large tables, sorts and expensive joins.| Table type | Index strategy |
|---|---|
| Product catalogue, read-heavy | More indexes acceptable for varied filters |
| Event log or payments ledger, insert-heavy | Minimal indexes, often only the primary key and a time column |
| Hot rows updated constantly | Avoid indexing frequently changing columns |
| Analytics | Consider a column store instead of many B-tree indexes |
-- Indexes never used since stats were last reset
SELECT s.relname AS table_name,
s.indexrelname AS index_name,
pg_size_pretty(pg_relation_size(s.indexrelid)) AS index_size,
s.idx_scan
FROM pg_stat_user_indexes s
JOIN pg_index i ON i.indexrelid = s.indexrelid
WHERE s.idx_scan = 0
AND NOT i.indisunique -- keep indexes that enforce constraints
ORDER BY pg_relation_size(s.indexrelid) DESC;
-- Drop without blocking writes
DROP INDEX CONCURRENTLY IF EXISTS idx_orders_status;
Check the result on the primary and every replica, since stats are per server and a replica may serve the queries that use the index.
-- Weak: separate indexes
-- CREATE INDEX ON orders (city);
-- CREATE INDEX ON orders (status);
-- CREATE INDEX ON orders (created_at);
-- Strong: matches the query shape, avoids a sort
CREATE INDEX idx_orders_city_status_created
ON orders (city, status, created_at DESC);
SELECT id, amount_paise FROM orders
WHERE city = 'Pune' AND status = 'PAID'
ORDER BY created_at DESC LIMIT 20;
Equality columns first, then the sort column. One index serves the filter and the ordering, with a third of the write cost.
Index Maintenance, Write Amplification, HOT Updates, Unused Indexes, Query Planner