← Back to Arena
Claude
Winner
823 votes (43.9%)
ChatGPT
612 votes (32.6%)
Gemini
298 votes (15.9%)
Llama
143 votes (7.6%)
"How do I fix a SQL query that's running slow?"
Start with EXPLAIN (or EXPLAIN ANALYZE in Postgres) to see what's happening. Usually it's one of these: 1) Missing index on WHERE/JOIN columns - add it. 2) SELECT * when you only need 2 columns - be specific. 3) No LIMIT on exploratory queries - add one. 4) Joining massive tables without filtering first - use subqueries or CTEs to shrink data before joining. 5) Using functions in WHERE clauses (WHERE YEAR(date) = 2024) - this kills index usage. Rewrite to WHERE date >= '2024-01-01'. Most slow queries are just missing indexes though. Check those first.
Steps to optimize slow SQL queries:
1. **Analyze**: Use EXPLAIN/EXPLAIN ANALYZE
2. **Index**: Add indexes on WHERE, JOIN, ORDER BY columns
3. **Reduce data**: Select only needed columns, add LIMIT
4. **Optimize JOINs**: Ensure join columns are indexed
5. **Avoid functions on columns**: WHERE YEAR(col) prevents index use
6. **Consider partitioning**: For very large tables
7. **Check statistics**: Run ANALYZE to update table stats
8. **Review subqueries**: Consider converting to JOINs
90% of the time it's an index problem. Run EXPLAIN, look for 'full table scan' or 'seq scan' - that's your bottleneck. Add an index. If it's still slow: are you selecting way more data than you need? Is there a join from hell creating a cartesian product? Are you using OR when you could use UNION? Index, index, index is the answer to most SQL performance questions.
Use EXPLAIN to analyze the query. Add indexes on columns used in WHERE and JOIN. Select only needed columns. Avoid functions on indexed columns. Consider rewriting complex subqueries as joins.
Cast Your Vote
Which AI gave the best response? Your vote counts!
Thanks for voting!
Your vote has been recorded