1 Query Optimization Techniques
TopA slow query that takes 5 seconds can often be rewritten to run in 5 milliseconds. Here are the most impactful optimization techniques.
The Optimization Checklist
| # | Technique | Impact | Effort |
|---|---|---|---|
| 1 | Add indexes on WHERE/JOIN/ORDER BY columns | 10x-10000x faster | Low |
| 2 | Select only needed columns (no SELECT *) | 2x-5x less data transfer | Low |
| 3 | Use LIMIT when you don't need all rows | Varies | Low |
| 4 | Avoid functions on indexed columns in WHERE | Prevents index use | Low |
| 5 | Use EXISTS instead of IN for large subqueries | 2x-10x on large data | Low |
| 6 | Avoid SELECT DISTINCT unless truly needed | Eliminates sort step | Low |
| 7 | Batch large operations (UPDATE/DELETE in chunks) | Reduces lock time | Medium |
| 8 | Denormalize for read-heavy queries | Eliminates JOINs | High |
Common Anti-Patterns
-- BAD: Function on indexed column kills the index
SELECT * FROM orders WHERE YEAR(order_date) = 2025;
-- GOOD: Range comparison uses the index
SELECT * FROM orders
WHERE order_date >= '2025-01-01' AND order_date < '2026-01-01';
-- BAD: Leading wildcard can't use index
SELECT * FROM users WHERE name LIKE '%ahmed';
-- GOOD: Trailing wildcard uses the index
SELECT * FROM users WHERE name LIKE 'ahmed%';Key Takeaways
- Indexing is the single biggest optimization lever
- Never apply functions to indexed columns in WHERE clauses
- Select only the columns you need; use LIMIT when possible
- Measure before optimizing — use EXPLAIN to identify the real bottleneck