SQL
Query Optimization Basics
Reading EXPLAIN Output
EXPLAIN ANALYZE SELECT ...;Look for:
- Sequential scans on large tables
- Nested loops with very high row counts
- Index scans
- Hash joins (often good)
Index Awareness
- Indexes help
WHERE,JOIN ON, andORDER BY - B-tree indexes (default) work well for
=,<,>,BETWEEN,LIKE 'prefix%' - Composite indexes rely on leftmost column order
- Indexes speed reads but add write overhead
Common Performance Pitfalls
| Problem | Fix |
|---|---|
SELECT * | Select only needed columns |
Function on indexed column in WHERE | Rewrite into range predicates |
NOT IN with NULLs | Prefer NOT EXISTS |
| Correlated subquery per-row | Rewrite as join or window function |
DISTINCT on large output | Usually indicates incorrect join logic |
UNION when dedup not needed | Use UNION ALL |