Database indexing is one of those topics where the theory is simple and the practice is full of surprises. Here are five lessons we learned from optimizing real production Postgres queries — the kind that actually break at scale.
Each one includes the EXPLAIN ANALYZE output and the fix.
01Lesson 1: The 8-second query that became 40ms with one index
A client had an admin dashboard that took 8 seconds to load. The query:
sql
SELECT FROM orders WHERE customer_id = 12345 ORDER BY created_at DESC LIMIT 20;
EXPLAIN ANALYZE showed a sequential scan over 4.2 million rows, then a sort:
Seq Scan on orders (cost=0.00..128000.00 rows=1 width=280) (actual time=4200.00..8100.00 rows=18000 loops=1)
Filter: (customer_id = 12345)
Sort: (created_at DESC)
Postgres was scanning every row in the table and sorting the matching rows in memory.
The fix was a composite index in the order the query uses them:
sql
CREATE INDEX idx_orders_customer_created ON orders (customer_id, created_at DESC);
After the index, the same query:
Index Scan using idx_orders_customer_created on orders (cost=0.43..820.00 rows=18000 width=280) (actual time=0.02..38.00 rows=20 loops=1)
8 seconds → 40ms. The key insight: the index matches the query's WHERE and ORDER BY exactly, so Postgres can read the top 20 rows directly from the index without sorting.
02Lesson 2: The index that was never used
We added an index to a query and it did not help. EXPLAIN still showed a sequential scan. The query was:
sql
SELECT FROM users WHERE LOWER(email) = 'customer@example.com';
The index was on email, but the query applies LOWER() to the column, so Postgres cannot use a plain B-tree index. The fix is an expression index:
sql
CREATE INDEX idx_users_email_lower ON users (LOWER(email));
After that, the query used the index and dropped from 300ms to under 5ms.
The lesson: indexes only match queries that use the exact expression the index was built on. If you wrap the column in a function, you need an index on that function.
03Lesson 3: The LIKE query that could not use an index
A search feature used:
sql
SELECT * FROM products WHERE name LIKE '%almond%';
A plain B-tree index on name cannot help here, because the leading % means the pattern can match anywhere in the string. Postgres has to scan every row.
The fix: for this kind of search, use a trigram index (from the pg_trgm extension):
sql
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE INDEX idx_products_name_trgm ON products USING GIN (name gin_trgm_ops);
After that, the same query dropped from 1.2 seconds to 15ms.
The lesson: LIKE '%...%' cannot use a B-tree. If you need substring search on Postgres, use pg_trgm — it is genuinely one of the best parts of Postgres and almost nobody uses it.
04Lesson 4: The over-indexed table
On one project we had a users table with 14 indexes. Writes were slow — every signup took longer than it should. EXPLAIN was fine for reads, but INSERT and UPDATE were the problem.
We audited every index. Only 4 were actually being used by any query. The other 10 were slowing down every write for no benefit.
The fix: we dropped the unused indexes. Signup time dropped from about 180ms to about 60ms. Write throughput roughly doubled.
The lesson: indexes are not free. Every index adds cost to every write. On write-heavy tables, audit your indexes regularly with pg_stat_user_indexes and drop anything unused:
sql
SELECT indexrelname, idx_scan, idx_tup_read
FROM pg_stat_user_indexes
WHERE idx_scan = 0
ORDER BY pg_relation_size(indexrelid) DESC;
Any index with idx_scan = 0 on a table that has been live for weeks is a candidate for removal.
05Lesson 5: The index that helped one query and broke another
We added an index to speed up a reporting query. It worked — the report dropped from 4 seconds to 300ms. But the next day, a different endpoint (which did a large UPDATE) started timing out.
The new index had added cost to every write to that table. The reporting query ran once an hour. The write endpoint ran thousands of times per hour.
The fix: we removed the index and instead pre-aggregated the report into a summary table, refreshed every 15 minutes by a scheduled job. The report now reads from the summary table in 20ms, and the write endpoint is unaffected.
The lesson: before adding an index, ask "how often does this query run, and how often does this table get written to?" If the query is rare and the writes are frequent, an index may not be the right fix. A materialized view, a summary table, or caching may be the better answer.
06The workflow we use now
Every slow query goes through the same process:
EXPLAIN (ANALYZE, BUFFERS)— always both.ANALYZEgives actual timings,BUFFERSshows I/O cost.- Check the row counts — is Postgres estimating correctly? If estimates are wildly off,
ANALYZEthe table first. - Look for sequential scans on large tables — that is usually where the time goes.
- Match the index to the query —
WHEREcolumns, thenORDER BYcolumns, in that order. - Check index usage — is the index actually used? If not, why not (function, LIKE pattern, type mismatch)?
- Measure again — never assume an index helped. Verify.
- Check write impact — confirm the index did not break a write path.
The whole process takes 15 minutes and saves hours of guessing.
07The takeaway
Most Postgres performance problems are index problems. But "add an index" is the wrong answer about half the time — sometimes you need an expression index, sometimes a trigram index, sometimes no index at all and a summary table instead.
The single most useful skill is reading EXPLAIN ANALYZE output. If you can do that, you can find the bottleneck. Everything else follows from there.