Subqueries and CTEs
7 pages · ~5 min✓ Reviewed
Builds on Aggregates and GROUP BY. Next up: Window Functions.
Subqueries and CTEs: The Mental Model
1. What a Subquery Is
- A subquery is a
SELECTnested inside another statement - Inner result acts as a value, a list or a table
- Scalar = exactly one row, one column; fits wherever an expression fits
sql
SELECT name, (SELECT MAX(salary) FROM emp) AS top FROM emp;
scalar subquery in the SELECT list
2. Placement Decides Shape
| Where | Takes |
|---|---|
SELECT / WHERE | scalar or list |
FROM | table |
| CTE | table, referenced many times |
3. Derived Table vs CTE
- Derived table: a subquery in
FROM, named by an alias - CTE:
WITH name AS (...), valid only for the one statement after it
sql
SELECT d.dept, d.a FROM (SELECT dept, AVG(salary) a FROM emp GROUP BY dept) d;
derived table with alias d
Alias on a derived table
Required in most engines. PostgreSQL 16+ and SQLite do not require one.
IN, EXISTS and Correlated Subqueries
1. IN and EXISTS
INcompares a value against the list the subquery returnsWHERE dept_id IN (SELECT id FROM dept WHERE city='Pune')EXISTSis true if the subquery yields at least one row- Selected columns are ignored, so
SELECT 1is conventional
2. Correlated Subqueries
- Refers to a column of the outer query
- Logically re-evaluated per outer row
CTEs and Recursive CTEs
1. CTE basics
sql
WITH high AS (SELECT * FROM emp WHERE salary > 50000), b AS (SELECT * FROM dept) SELECT * FROM high;
chain several with commas, one WITH
- Prefer over a nested derived table: name each step, reuse it many times
- No guarantee of materialization: the engine decides
2. Recursive CTE
- Anchorstart rows
- UNION ALL
- Recursive memberreads the CTE
- Stopno rows returned
UNION vs UNION ALL and Choosing a Form
1. UNION vs UNION ALL
| UNION | UNION ALL | |
|---|---|---|
| Duplicates | removed | kept |
| Extra step | sort or hash | none |
| Speed | slower | faster |
| Use when |
Common Mistakes with Subqueries and Set Operators
1. Silent wrong results
NOT INwith one NULL in the list returns zero rows (x <> NULLis unknown)- Fix:
NOT EXISTS, or filter NULLs out of the subquery UNIONwhereUNION ALLfits: needless sort, drops real duplicates
sql
SELECT c.id FROM cust c WHERE NOT EXISTS ( SELECT 1 FROM orders o WHERE o.cust_id = c.id );
NULL-safe anti-join
2. Errors
Subqueries, CTEs and Set Operators Cheat Sheet
1. Subquery and CTE forms
| Form | Gives |
|---|---|
(SELECT MAX(x) FROM t) | 1 row, 1 col: SELECT, WHERE, HAVING |
col IN (SELECT ...) | a list |
EXISTS (SELECT 1 ... WHERE i.k = o.k) | true/false per outer row |
FROM (SELECT ...) d | table; alias in most engines |
Check yourself
orders.cust_id contains one NULL. What does SELECT name FROM customers WHERE id NOT IN (SELECT cust_id FROM orders) return?
- Zero rows.
id <> NULLis unknown, so no row passes.- Fix: use
NOT EXISTS.
A recursive CTE uses UNION ALL and lvl+1 on data with a cycle. What happens?
- It loops forever.
- Fix: add
WHERE t.lvl < 10. UNIONwould not help, becauselvlmakes every row distinct.