Why your SQL queries are slow (and how to fix them)
Most backend engineers write SQL that works. Few write SQL that's fast.
I've spent years optimizing queries in production Go services β from startups handling thousands of requests to systems processing millions of rows per second. The patterns that make queries fast are learnable, but most engineers never get explicit training on them.
Here are three things I see constantly in slow codebases:
1. Missing composite indexes (or wrong column order)
-- You have this index:
CREATE INDEX idx_orders_user ON orders(user_id);
-- But your query filters on both:
SELECT * FROM orders WHERE user_id = $1 AND status = 'pending' ORDER BY created_at DESC;
-- You need this instead:
CREATE INDEX idx_orders_user_status_created ON orders(user_id, status, created_at DESC);Column order in composite indexes matters. The optimizer can't skip columns.
2. N+1 queries hidden in your ORM
Your Go code looks clean, but under the hood it's firing 200 queries when one join would do. EXPLAIN ANALYZE doesn't lie β check your actual query count.
3. Ignoring the query planner's cost model
Seq Scan isn't always bad. Index Scan isn't always good. The planner makes decisions based on statistics, and if your stats are stale (ANALYZE hasn't run), it makes bad decisions.
---
I built a full course covering these patterns and much more β from reading EXPLAIN output to production-grade Go + PostgreSQL optimization. It's designed for mid-to-senior backend engineers who want to ship fast queries, not just correct ones.
Check it out if you're serious about database performance. π₯
