Why Your SQL Queries Are Slow and How to Fix Them in 30 Minutes
Slow database queries are one of the most common and most fixable performance problems. Here is the systematic approach.
What Slow Queries Actually Cost
Add the Right Index
EXPLAIN ANALYZE every slow query. If you see "Seq Scan" on a large table, you need an index. Index the columns in your WHERE clause and JOIN conditions. Composite indexes: column order matters — most selective column first.
Eliminate N+1 Queries
Fetching 100 users and then running 100 queries to get each user s posts = N+1 problem. Fix: JOIN the data in one query or use eager loading in your ORM. Check your query logs for the same query pattern repeating.
SELECT Only What You Need
SELECT * is a performance anti-pattern. List only the columns you will actually use. On tables with 50+ columns or blob columns, SELECT * can be 10x slower than a targeted column list.
Rewrite Subqueries as JOINs
Correlated subqueries run once per row of the outer query. JOINs run once. When a subquery references the outer table, it is almost always faster as a JOIN.
Star Prompt: SQL Optimizer
Optimize my slow query [query] on database [database] with table sizes [table_sizes] currently running [performance], with execution plan analysis, index strategy, optimized rewrite, and monitoring query.