The SQL Performance Engineer diagnoses and rewrites slow queries. Most query performance problems are in one of four places: missing indexes, poor join order, N+1 patterns, or inefficient subqueries that can be replaced with window functions. Diagnose with EXPLAIN ANALYZE before rewriting - never guess at the cause.
Reading EXPLAIN ANALYZE
EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)
SELECT o.*, u.email
FROM orders o
JOIN users u ON u.id = o.user_id
WHERE o.status = 'pending'
ORDER BY o.created_at DESC
LIMIT 50;
-- Key metrics to read:
-- "Seq Scan on orders (rows=142381 width=84)" → missing index (sequential full scan)
-- "Rows Removed by Filter: 141891" → filter is very selective → add index
-- "actual time=0.024..12.3 rows=490" → 12ms spent; 490 rows matched
-- "Buffers: shared hit=3421 read=8912" → 8912 blocks read from disk → slow
-- "Hash Join" with "rows=1" → bad estimate → run ANALYZE to update stats
-- After diagnosis:
-- Seq Scan + high Rows Removed → CREATE INDEX ON orders(status)
-- Bad row estimates → ANALYZE orders; (or VACUUM ANALYZE)
Query Rewriting Patterns
-- Replace correlated subquery with JOIN (often 10-100× faster)
-- ❌ Correlated subquery - executes once per row of users
SELECT u.id, u.email,
(SELECT COUNT(*) FROM orders o WHERE o.user_id = u.id AND o.status = 'completed') AS order_count
FROM users u;
-- ✅ LEFT JOIN with aggregation - single scan of orders
SELECT u.id, u.email, COALESCE(o.order_count, 0) AS order_count
FROM users u
LEFT JOIN (
SELECT user_id, COUNT(*) AS order_count
FROM orders WHERE status = 'completed'
GROUP BY user_id
) o ON o.user_id = u.id;
-- Replace multiple self-joins with window functions
-- ❌ Separate queries for current + previous period totals
-- ✅ Single query with LAG() window function
SELECT
DATE_TRUNC('month', created_at) AS month,
SUM(total_cents) AS revenue,
LAG(SUM(total_cents)) OVER (ORDER BY DATE_TRUNC('month', created_at)) AS prev_revenue,
SUM(total_cents) - LAG(SUM(total_cents)) OVER (ORDER BY DATE_TRUNC('month', created_at)) AS growth
FROM orders
GROUP BY 1
ORDER BY 1;
Query Optimisation Checklist
- Run
EXPLAIN (ANALYZE, BUFFERS)- read actual vs estimated rows, find Seq Scans - Check for missing indexes:
pg_stat_user_tables- highseq_scan+seq_tup_read= candidate for index - Rewrite correlated subqueries as JOINs
- Replace multiple JOINs on aggregates with window functions
- Use
LIMITwithOFFSETonly up to page 10; use keyset pagination for deeper pages - Run
ANALYZE table_name;if row estimates are wildly off