Part 06 / Stage 2
Subqueries, CTEs and set operations
Goal: Break a hard question into steps — queries inside queries, named steps with WITH, row-by-row LATERAL lookups, and stacking result sets with UNION and friends. Time: ~2 hours
What you will learn
- Scalar subqueries: one query used as a single value
- Filtering by another query:
INandEXISTS - The
NOT INtrap — one NULL, zero rows — and whyNOT EXISTSis the fix - Correlated subqueries: the inner query that sees the outer row
- Derived tables: a subquery as your FROM
LATERAL: the per-row subquery join, and "latest order per customer"- Common table expressions:
WITHfor readable, step-by-step queries UNION,INTERSECT,EXCEPT— and ALL
Everything runs on shopdb. Drifted? psql -d shopdb -f shopdb.sql.
Topics in this part
Practice
SQL workbench — write and run queries here
Press Run and PostgreSQL loads right in your browser (a one-time download of about 16 MB; after that it works offline). It comes seeded with shopdb, and statements share one session per page — like a psql window. Reset data rebuilds shopdb. Your queries never leave this page. Lessons were captured on PostgreSQL 17; the in-browser server is PostgreSQL 19 (via PGlite), so the rare output detail can differ.
Each topic above carries its own exercise and solution — open a topic and scroll to its exercise. All 8 exercises are also listed on the SQL Practice page.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
NOT IN (subquery) over a nullable column |
One NULL silently yields zero rows | NOT EXISTS |
| Forgetting the derived table's alias | subquery in FROM must have an alias |
) AS name |
| Scalar subquery returning many rows | more than one row returned... |
Aggregate it, or LIMIT 1 with an ORDER BY |
| UNION when you meant UNION ALL | Rows silently de-duplicated (and slower) | ALL unless de-dup is the point |
| Plain FROM subquery referencing outer tables | invalid reference to FROM-clause entry |
LATERAL |
| Ten levels of nesting | Unreadable, unreviewable | WITH — name the steps |
Quick recap
- A scalar subquery returns one value from brackets; it errors on many rows and yields NULL on none.
- IN/EXISTS both test membership; negated, only NOT EXISTS survives NULLs.
- Correlated subqueries see the outer row — the natural per-row question shape.
- A derived table aggregates first and queries second, which kills fan-out; LATERAL is the per-row version that can return whole rows, as in "latest order per customer".
- WITH names each step, reads top-down, and lets every step build on the previous one.
- UNION stacks results and de-duplicates them, UNION ALL just stacks, and INTERSECT/EXCEPT handle the remaining set logic.
Checklist
Before Part 7, make sure you can:
- Filter against an average without hard-coding it.
- Explain the NOT IN trap to a colleague in two sentences, with the fix.
- Compute per-customer totals in a CTE and query them.
- Fetch each customer's latest order with LATERAL.
- Say when UNION ALL beats UNION, and what EXCEPT does.
Read more: the official subquery expressions reference and the WITH queries chapter.