Most of the projects I inherit are not slow because PostgreSQL is slow. They are slow because of one of five indexing habits. None of them is exotic, and all of them take an afternoon to fix.
1. The column order is wrong
A B-tree index keeps its entries sorted by the first column, then the second, and so on. An index on (customer_id, created_at) answers "everything for this customer, newest first" beautifully — and does almost nothing for "everything from the last seven days" on its own. Put the column you filter on by equality first, and the one you sort or range over second:
-- Serves: WHERE customer_id = $1 ORDER BY created_at DESC
CREATE INDEX CONCURRENTLY bookings_customer_created
ON bookings (customer_id, created_at DESC);
If both questions matter, you need two indexes. That is fine. Two useful indexes cost less than one that helps nobody.
2. Foreign keys without indexes
PostgreSQL does not index the referencing side of a foreign key for you. Every join, every ON DELETE and every "show me the orders for this customer" then reads the whole child table until the planner finds a better way. If you join on it or filter by it, index it.
3. Hoping LIKE '%term%' will use a B-tree
A B-tree can find a prefix. It cannot find a substring in the middle, so WHERE name LIKE '%gmbh%' is a sequential scan — forever, however many indexes you add. For search boxes, a trigram index does the job:
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE INDEX customers_name_trgm ON customers USING gin (name gin_trgm_ops);
4. Ten single-column indexes where two would do
Every index is maintained on every insert and update. Past a handful, a write-heavy table spends more time updating indexes than data, and PostgreSQL stops being able to use fast "HOT" updates altogether. Before adding one, ask whether a composite index you already have could serve the query if its column order were different.
5. Never reading EXPLAIN
The planner works from statistics, and statistics go stale after large imports. The single most useful habit is to read the plan for the query you are about to optimise — and to compare the estimated row count with the actual one:
EXPLAIN (ANALYZE, BUFFERS)
SELECT ... ;
If the estimate says 40 rows and the actual says 400,000, the planner is choosing a plan for a different database. Run ANALYZE, look again, and only then reach for an index.
A short checklist
- Equality columns first, range and sort columns second.
- Index every foreign key you join on or filter by.
- Substring search needs a trigram index, not hope.
- Count the indexes on write-heavy tables. Fewer, wider ones usually win.
- Estimates versus actuals, every time.
None of this is new. It is just easier to remember the week after it bit you.