Bored Analyst
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, and ORDER 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

ProblemFix
SELECT *Select only needed columns
Function on indexed column in WHERERewrite into range predicates
NOT IN with NULLsPrefer NOT EXISTS
Correlated subquery per-rowRewrite as join or window function
DISTINCT on large outputUsually indicates incorrect join logic
UNION when dedup not neededUse UNION ALL

On this page