Reading Room · Module 05
Track 0/9 (0%)
Course completion
Module 05 · Subqueries~22 min · 7 worked queries

Scalar, Correlated & EXISTS Subqueries

Nest independent and row-correlated queries inside IN, comparison operators, EXISTS, SELECT projections, and FROM derived tables.

Trace Live in StudioAll Modules
Core Relational Rule
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

  1. 01.

    Scalar and IN subqueries can run once upstream when they do not reference columns from the outer row.

  2. 02.

    Correlated subqueries and EXISTS re-evaluate logically per outer candidate tuple, stopping on the first match.

  3. 03.

    Derived tables inside FROM act like anonymous temporary views fed directly into outer JOINs or GROUP BYs.

Frequent Pitfall to Avoid
Writing WHERE col NOT IN (SELECT nullable_col ...) instead of NOT EXISTS, resulting in an unexpectedly empty output.

Interactive Module Lab · Subqueries

30. The NOT IN trap with NULL — sql
SELECT name
FROM departments
WHERE id NOT IN (SELECT department_id FROM users);
Execution Stages4 steps
Stage 01 · FROM

SOURCE: DEPARTMENTS

4 in → 4 out

Scanned 4 rows from table 'departments'.

#idnamebudgetlocationstate
11Engineering850,000San Franciscokeep
22Product420,000Londonkeep
33Design250,000Torontokeep
44Marketing300,000New Yorkkeep
Inspect each evaluated clause in 30. The NOT IN trap with NULL or animate every row moving between stages in Studio.Open 30. The NOT IN trap with NULL in Studio →

Worked Presets in This Module

26. Nested Subquery (IN)

The inner query runs once and produces a list. The outer query then keeps rows whose id is in that list.

27. Scalar subquery: above the average

A subquery that returns one value can be used like a number inside WHERE.

28. Correlated subquery

The inner query is re-run for every outer row, comparing each person with their own department.

29. EXISTS and NOT EXISTS

EXISTS only asks "is there at least one row?", so it is true or false for each outer row.

30. The NOT IN trap with NULL

One NULL in the list makes NOT IN unknown for every row, so this returns nothing. Compare with NOT EXISTS.

31. Subquery in FROM (derived table)

The inner query becomes a temporary table that the outer query reads from and filters.

32. Subquery inside SELECT

A correlated scalar subquery can compute one extra column per row.

Navigation

LivePreparation

Client-side workspace · saved locally