Subqueries and CTEs
Structuring multi-step logic with subqueries and common table expressions so complex queries stay readable and testable.
Intermediate · about 5 hours · difficulty 3/5
Learn first: Joins and Combining Tables
Most real analyses need several steps: find each user's first order, then group users by that month, then compute retention. Subqueries and CTEs let you express those steps.
Subqueries
- Scalar subquery: returns one value, e.g.
WHERE amount > (SELECT AVG(amount) FROM orders). - IN / EXISTS subquery: filters by membership.
- Derived table: a subquery in FROM that you treat like a table.
- Correlated subquery: references the outer row; powerful but can be slow.
Common table expressions
WITH first_orders AS (
SELECT customer_id, MIN(order_date) AS first_order_date
FROM orders
GROUP BY customer_id
),
monthly AS (
SELECT DATE_TRUNC('month', first_order_date) AS cohort_month,
COUNT(*) AS new_customers
FROM first_orders
GROUP BY 1
)
SELECT * FROM monthly ORDER BY cohort_month;
CTEs read top to bottom like a recipe. Name each one for what it contains, keep each step small, and run them individually while debugging.
Recursive CTEs
WITH RECURSIVE walks hierarchies (org charts, category trees) or generates series. Occasionally useful; not daily work.
Pitfalls: deeply nested subqueries no one can read, and huge CTE chains that repeat the same scan. Move on when you can refactor a nested query into named CTE steps and validate each step's row count.
Key concepts
- Scalar and IN subqueries
- EXISTS and correlated subqueries
- Derived tables
- WITH clauses (CTEs)
- Structuring multi-step logic
- Recursive CTEs
Mini project
Using the Olist dataset, write a CTE-based query that finds each customer's first purchase month and counts how many of them bought again within 90 days.
Check yourself
When would you choose EXISTS over IN, and what NULL-related trap does NOT IN have?
Free resources
- Mode SQL Tutorial (Mode)
- PostgreSQL: WITH queries (PostgreSQL)
- Advanced SQL (Kaggle)