Faragiri

Learn Subqueries SQL

A single NULL that makes a correct-looking query return no rows, the difference between a subquery that runs once and one that runs per row, and where each form belongs.

4Sections
3Min read
4Depth

Recommended Before This

0 / 2
  • SELECT
  • Joins

Here is a query that returns nothing and is not wrong.
SELECT name FROM fg_makers WHERE id NOT IN (SELECT maker_id FROM
fg_kilns)
answers no rows, measured on MySQL 8.4 on
2026-09-02, when the correct answer is two makers. The subquery returns a NULL
among its values, and id NOT IN (1, 3, NULL) is never true: it is
unknown, and WHERE keeps only what is true.

Two fixes, and one of them is better.
NOT EXISTS answers Behrouz and Kaveh
correctly and has no NULL problem by construction. Adding
WHERE maker_id IS NOT NULL inside the subquery also works and
relies on somebody remembering. Use NOT EXISTS for an absence test,
always, and treat any NOT IN over a subquery as a bug waiting for a
nullable column.

Correlated or not, which is the performance question

A plain subquery runs once and its result is used by the outer query. A
correlated subquery references the outer row, so it runs once per outer row:
SELECT m.name, (SELECT COUNT(*) FROM fg_kilns k WHERE k.maker_id = m.id)
FROM fg_makers m
answers 2, 0, 1, 0 and executes the inner query four
times.

One question, before writing it

What decides whether a subquery runs once or a million times

The fork is not about style or readability: one arm is a single execution and the other is one per row of the outer query.

Does the subquery mention the outer query's alias?
  • no
    It runs onceThe result is computed and then used by the outer query
    • IN with a list of values, and EXISTS with a constant condition
    • cost is the subquery, once, whatever the outer row count
  • yes
    It runs per outer rowCorrelated. Four rows is nothing and a million is the whole query
    • a count in the select list, referencing m.id
    • the fix is a join with a GROUP BY, computing every count in one pass

Engines rewrite some correlated subqueries into joins and it is not guessable which. The fork tells you what to check in the plan rather than what the plan will say.

Interactive Practice Lab

Edit and run this snippet directly in your browser (zero setup)

SQL
CREATE TABLE workshop_orders (id INTEGER PRIMARY KEY, supplier TEXT, qty INTEGER, city TEXT);INSERT INTO workshop_orders VALUES (1, 'Sepehr', 15, 'Ardabil'), (2, 'Aria', 47, 'Tabriz'), (3, 'Sepehr', 22, 'Ardabil'), (4, 'Nima', 31, 'Tehran');SELECT supplier, COUNT(*) AS deliveries, SUM(qty) AS total_qtyFROM workshop_ordersGROUP BY supplierORDER BY total_qty DESC;

Live Big-O Complexity & Binary Search Race Lab

Compare complexity curves at scale and watch Linear vs Binary Search race live.

At four rows that is nothing. At a million it is the same shape as the N plus
one problem an ORM produces, and the fix is the same: turn it into a join with a
GROUP BY, which computes every count in one pass. The tell is a subquery that
mentions the outer query's alias.

Where each form belongs

  • IN with a list from a subquery, for a simple membership test
    with no nulls
  • EXISTS and NOT EXISTS for presence and absence,
    which is the safest pair and often the fastest, because the engine can stop at
    the first match
  • A subquery in FROM, a derived table, to aggregate before joining, which is
    the fix for the row multiplication a join causes
  • A common table expression with WITH, for the same thing with a
    name, which makes a long query readable and can be referenced twice

One more form is worth knowing because it removes a whole category of
correlated subquery: a lateral join, spelled LATERAL in most engines
and CROSS APPLY in SQL Server. It lets a joined subquery reference
the row it is being joined to, which is what a correlated subquery does, except
that the engine treats it as a join and can plan it as one. The usual use is the
three most recent rows per group, which is awkward with a plain subquery and one
clause with this.

Matching shape to job

Five subquery forms and where each belongs

Picking the right form prevents NULL traps, avoids join row multiplication, and gives the planner a join it can optimise.

Subquery forms
  • IN (subquery)Simple membership test when the column cannot contain NULLs
  • EXISTS / NOT EXISTSSafest presence and absence check; stops at the first match
  • FROM derived tableAggregate child rows before joining so totals do not double
  • WITH (CTE)Named intermediate result that stays readable and reusable
  • LATERAL / CROSS APPLYPer-row joined subquery for top recent rows per group
  • IN (subquery)Simple membership test when the column cannot contain NULLs
  • EXISTS / NOT EXISTSSafest presence and absence check; stops at the first match
  • FROM derived tableAggregate child rows before joining so totals do not double
  • WITH (CTE)Named intermediate result that stays readable and reusable
  • LATERAL / CROSS APPLYPer-row joined subquery for top recent rows per group

Use NOT EXISTS instead of NOT IN whenever the subquery column could ever contain a NULL.

What to run in 2026

Common table expressions are the tool, free and in every current engine.
WITH kiln_counts AS (...) SELECT ... names an intermediate result,
so a query that would be three levels of nesting becomes a sequence that reads
top to bottom. It replaced nesting subqueries inside subqueries, which is
correct and unreadable after the second level.

What to run in 2026

Readable CTEs backed by EXPLAIN verification

Common table expressions flatten nested subqueries into named steps, while EXPLAIN confirms how the optimiser executes them.

Predictable SQL subqueries
  • WITH cte AS (...)Turns three levels of nesting into a top-to-bottom sequence of named results
  • EXPLAIN plan checkShows whether a correlated subquery runs per row or was rewritten into a join

Built into every current SQL engine

Never guess whether the optimiser unnested a correlated subquery; read the plan.

EXPLAIN is the second, free with every engine, and it is how you
find out whether a correlated subquery is being executed per row or has been
rewritten by the optimiser into a join. Engines do rewrite some of them, and
which ones is not guessable, so the plan is the only answer. It replaced
assuming either the best or the worst.

Where this stalls people

The stall is nesting until it works. A subquery inside a subquery inside a
join is a query nobody can modify, including the person who wrote it last week,
and it usually exists because each layer was added to fix the layer below.

Where subqueries stall people

Peeling back layers added to patch the layer below

Stacking subqueries inside joins creates queries nobody can safely edit until each layer is unrolled into a named CTE step.

  1. Original base queryFirst inner subqueryWrapped around the core lookup to adjust a result
  2. 02Second nested layerAdded outside to fix an unexpected count or row
  3. 03Outer join wrapperToo tangled to modify without breaking another layer
  4. 04CTE rewrite (step by step)Unrolls the layers and often exposes two doing the same work

Rewrite nested queries into sequential CTEs before debugging; clarity exposes redundant layers immediately.

Rewrite it with common table expressions, one named step at a time, before
trying to fix anything. Half the time the rewrite reveals that two of the layers
were doing the same thing. The joins these replace are
combining tables, and the four
kinds
, the counting inside them is
counting, summing and
grouping by
, and the same problem arriving through an object layer is
the layer between your
objects and the tables
, inside
the language for asking a database
questions
.

Alongside this

Above this