Common SQL Query Optimization Tips
Most slow queries are slow for predictable reasons. Here are the optimization tips I apply again and again across different codebases. Slow queries usually fail in predictable ways. After optimizing queries across several codebases, I notice the same patterns causing slowness: selecting too much, filtering too late, wrapping indexed columns in functions, and ignoring what the execution plan is trying to tell me. Here are the optimization tips I apply most often, in roughly the order I check them. Start with EXPLAIN ANALYZE Optimizing a query without looking at the execution plan is guessing. EXPLAIN ANALYZE shows what the database actually does when it runs the query: which tables are scanned, which indexes are used, what join strategies are chosen, and how much time each step takes. The plan tells you where the time goes, and that is where you optimize. EXPLAIN ANALYZE SELECT u.name, COUNT(o.id) AS order_count FROM users u LEFT JOIN orders o ON u.id = o.user_id WHERE u.created_at >= '2026-01-01' GROUP BY u.name; I look for sequential scans on large tables, which means the database is reading every row instead of using an index. I look for nested…