Query plans & optimization
Read EXPLAIN: scan vs seek, join order, spilling, partition pruning. Knowing why a query is slow separates engineers from SQL writers.
The mental model
A query planner is a **GPS routing engine for data**. You state the destination (the result set, declaratively); the planner enumerates routes (scan this index or that table, join in this order with that algorithm), estimates each route's cost using a *map* — table statistics — and drives the cheapest one. EXPLAIN shows you the chosen route; EXPLAIN ANALYZE drives it and reports actual traffic.
The one idea that explains most slow queries: **the planner never looks at your data while planning — only at statistics about it.** Row counts, distinct-value counts, histograms, min/max per column, collected by ANALYZE (Postgres), automatically (Snowflake/BigQuery), or by ANALYZE TABLE (Spark). When the map is stale or the terrain is weird (correlated columns, skew, fresh loads), the GPS confidently routes you through a swamp: a nested-loop join that touches 100M rows because it estimated 12.
Why this skill exists: without it you can only respond to a slow query with folklore — add an index, add compute, add a cache. Reading the plan turns "the dashboard is slow" into "the join order is inverted because the filter estimate is off by 10,000x", which is a fixable statement. It is also the sharpest interview discriminator in data engineering: anyone can write SQL; engineers explain why it is slow.
- Deep dive
- Internal architecture
- Real-world use cases
- Best practices
- Common mistakes
- Performance
- Security
- Production troubleshooting
- Advantages & disadvantages
- Alternatives
- Interview expectations
- Interview questions
- Facts to remember
- Cheat sheet
- Quick revision