Scalar, Correlated & EXISTS Subqueries
Nest independent and row-correlated queries inside IN, comparison operators, EXISTS, SELECT projections, and FROM derived tables.
NOT IN returns zero rows if the inner query emits even a single NULL because SQL three-valued logic evaluates x != NULL as UNKNOWN.Module 05 · Subqueries · Reading Room
Mental Model
- 01.
Scalar and IN subqueries can run once upstream when they do not reference columns from the outer row.
- 02.
Correlated subqueries and EXISTS re-evaluate logically per outer candidate tuple, stopping on the first match.
- 03.
Derived tables inside FROM act like anonymous temporary views fed directly into outer JOINs or GROUP BYs.
Interactive Module Lab · Subqueries
30. The NOT IN trap with NULL — sqlSELECT nameFROM departmentsWHERE id NOT IN (SELECT department_id FROM users);
SOURCE: DEPARTMENTS
Scanned 4 rows from table 'departments'.
| # | id | name | budget | location | state |
|---|---|---|---|---|---|
| 1 | 1 | Engineering | 850,000 | San Francisco | keep |
| 2 | 2 | Product | 420,000 | London | keep |
| 3 | 3 | Design | 250,000 | Toronto | keep |
| 4 | 4 | Marketing | 300,000 | New York | keep |
Worked Presets in This Module
The inner query runs once and produces a list. The outer query then keeps rows whose id is in that list.
A subquery that returns one value can be used like a number inside WHERE.
The inner query is re-run for every outer row, comparing each person with their own department.
EXISTS only asks "is there at least one row?", so it is true or false for each outer row.
One NULL in the list makes NOT IN unknown for every row, so this returns nothing. Compare with NOT EXISTS.