Subqueries
- Scalar subqueries. A subquery in parentheses returns a value or set another query consumes: a question inside a question.
- IN and EXISTS. IN matches against a subquery’s list; EXISTS just asks whether any row matches: usually the faster intent.
- Correlated subqueries. A correlated subquery references the outer row, re-answering per row: powerful, and worth watching in plans.
Common Table Expressions
- WITH. A CTE: WITH recent AS (SELECT …): names a subresult so the main query reads like prose.
- Chaining CTEs. CTEs chain: each one builds on the last, turning a nested monster into a readable pipeline.
- CTEs and performance. A CTE is not automatically materialised: semantics first, then check the plan if it matters.
Breaking Complex Queries Into Stages
- Stage the logic. Hard queries decompose into stages: filter, join, aggregate, rank: one CTE each, tested as you go.
- Debugging by stage. Debug a wrong result by selecting each CTE alone: the stage where counts go wrong names the bug.
- Readable analytics. The maintainable analytics query is a story: named steps a reviewer can verify one by one.
Before and after this level
- Before: Level 4: Aggregation: GROUP BY, Aggregate Functions, HAVING and Analytical Summaries.
- Next: Level 6: Window Functions: Ranking and Partitioning, Running and Moving Calculations, Advanced Analytical Queries.
In the app each of these ideas is taught and then asked back, and the level ends with a checkpoint and flashcards. See Checkpoints and flashcards.
Frequently asked questions
What does SQL Level 5: Subqueries & CTEs cover?
Subqueries, Common Table Expressions, Breaking Complex Queries Into Stages: 3 lessons and 9 ideas.
What should I know before this level?
The level before it, Level 4: Aggregation, which covers GROUP BY, Aggregate Functions, HAVING and Analytical Summaries.