Loading

T11 SQL · Lesson 7

Subqueries

Ask a question inside a question: compare each row with a value worked out by another query, keep the rows whose value is IN another query's answer, test whether matching rows EXIST, let an inner query look at the outer row, and build a query on another query's answer with FROM and WITH.

  • use a subquery that gives one value, such as an average, inside WHERE or SELECT
  • keep rows with IN and a subquery, and avoid the NULL trap of NOT IN
  • test for matching rows with EXISTS and NOT EXISTS
  • write a correlated subquery that is worked out again for each outer row
  • query another query's answer, with a subquery in FROM or with WITH
  • choose between a subquery and a join for the same question
About 75 minutesChecked against SQLite's command-line shell, sqlite3, the "sqlite-tools-linux-x64-3540100.zip" of sqlite.org (the kit compares every SQL block with it, in its sandbox; the page runs the small sqlite3 of plan 34) 3.54.1 (2026-11-21); GNU Bash on the laptop (the kit compares every shell block with it, in a sandbox) 5.3.9 (2026-11-21)Play this lesson's games

The back cover

Some questions cannot be asked in one go. Which students scored above the class average? First you need the average. Which customers never ordered? First you need the ones who did. A clerk would write the first answer on a slip and then read down the list.

These pages fold the slip into the question. A query in brackets inside another one gives a value, a list or a whole table, and the outer query uses it. EXISTS asks whether any match is there at all, a correlated subquery asks again for every row, and WITH names each step of a long question. And one NULL hides a famous trap.

Before you start

The story: Questions inside questions

The halls' questions have grown harder. Which gauges read above the works' average? A clerk must first work out the average, write it on a slip, and then go down the page comparing every reading with the slip.

Which halls have no gauge at all? Another clerk copies every hall number the gauges use onto a slip, then checks each hall against it, and the compass's blank space confuses the slip. A third question needs each gauge compared with the average of its own hall, a new slip for every hall.

Registrar Nadia Folio gathers the slips. "Ask the ledger, not your memory," she says, "and not your slips either. A question can hold another question inside it, in brackets. The ledger answers the inner one first, and uses its answer in the outer one."

Some questions need another answer first. Which gauges read above the average? First you need the average; then you compare. Which halls have no gauge? First you need the halls the gauges use; then you look for the rest.

A subquery is a query written inside another one, in brackets. SQLite works out the inner query, and the outer query uses its answer: one value, a list of values, or a whole table. This lesson writes them in WHERE, in SELECT and in FROM, meets EXISTS, and gives a subquery a name of its own with WITH. It is the last lesson of the SQL track.

The ledger is lesson 06's: the halls, and the nine gauges. Here are the columns this lesson uses most:

query.sql (ledger.db holds halls and gauges, as in lesson 06)

SELECT * FROM halls;
SELECT id, name, hall_id, reading FROM gauges;

Terminal: sqlite3 ledger.db < query.sql

╭────┬────────────────┬───────────────╮
│ id │      name      │    keeper     │
╞════╪════════════════╪═══════════════╡
│  1 │ Engine Hall    │ Ines Tappet   │
│  2 │ Clock Tower    │ Hakim Verge   │
│  3 │ Couriers' Yard │ Dalia Waybill │
│  4 │ Archive        │ Yusra Hollis  │
╰────┴────────────────┴───────────────╯
╭────┬──────────┬─────────┬─────────╮
│ id │   name   │ hall_id │ reading │
╞════╪══════════╪═════════╪═════════╡
│  1 │ boiler   │       1 │    96.5 │
│  2 │ pump     │       1 │     4.2 │
│  3 │ fan      │       1 │  1200.0 │
│  4 │ chimney  │       3 │ NULL    │
│  5 │ pendulum │       2 │     2.0 │
│  6 │ kettle   │       3 │    88.0 │
│  7 │ bell     │       2 │   440.0 │
│  8 │ valve    │       1 │     4.2 │
│  9 │ compass  │ NULL    │   270.0 │
╰────┴──────────┴─────────┴─────────╯

Keep the two loose ends of lesson 05 in mind. The compass has no hall: its hall_id is NULL. The Archive has no gauges: no hall_id is 4. Both come back, and the compass's NULL sets the most famous trap in this lesson.

This lesson builds on these ideas. Each one has a tiny example, so you can check that you remember it.

What you already knowA tiny exampleWhere it comes back
AVG, MAX and COUNT turn many rows into one value.SELECT AVG(reading) FROM gauges;A subquery that gives one value.
An aggregate cannot go in WHERE.lesson 04's misuse of aggregateThe subquery is the way round it.
IN keeps a value found in a list.unit IN ('C', 'bar')A list made by a query.
NULL makes a comparison not known.reading = NULL is never trueThe NOT IN trap.
JOIN lays two tables side by side.gauges g JOIN halls h ON g.hall_id = h.idThe same questions, asked another way.
LEFT JOIN ... IS NULL finds rows with no match.the ArchiveNOT EXISTS finds them too.
Short table names with AS.FROM gauges AS gTelling the inner and outer gauges apart.
GROUP BY gives one row per group.GROUP BY hall_idA table of totals to query again.
A function that calls another in JavaScript.Math.max(...list.map(f))The inner answer feeds the outer one.
A loop inside a loop.for (g of gauges) for (h of halls)A subquery run again for each row.

By the end of this lesson you will be able to:

  • use a subquery that gives one value, such as an average, inside WHERE or SELECT;
  • keep rows with IN and a subquery, and avoid the NULL trap of NOT IN;
  • test for matching rows with EXISTS and NOT EXISTS;
  • write a correlated subquery that is worked out again for each outer row;
  • query another query's answer, with a subquery in FROM or with WITH;
  • choose between a subquery and a join for the same question.

How to follow this lesson

As before, each block is a file of SQL and the command sqlite3 ledger.db < query.sql. To understand a subquery, run the inner query on its own first: its answer is exactly what the outer query receives.

Every block was also run with the real sqlite3 3.54.1 in a real terminal, and printed exactly what you see.

In one line

A subquery is a query in brackets inside another; SQLite answers the inner one first, and the outer one uses its answer as a value, a list or a table.

A question inside a question

At a glance

A subquery in brackets can stand for one value, such as the average reading, anywhere a value can go.

SQLite works out the inner query first, then uses its answer in the outer one, so a report compared with the average stays right when the data changes. The brackets are required. An aggregate cannot sit in WHERE on its own, but a subquery that works it out can. If the inner query gives several rows, SQLite quietly uses the first.

Take a guess: What does a one-value subquery give when its inner query finds no rows at all?

Which gauges read above the average? Two steps. First, the average:

query.sql (ledger.db holds halls and gauges, as in lesson 06)

SELECT AVG(reading) FROM gauges;

Terminal: sqlite3 ledger.db < query.sql

╭──────────────╮
│ AVG(reading) │
╞══════════════╡
│     263.1125 │
╰──────────────╯

Then the gauges above 263.1125. Rather than copy that number by hand, put the first query, in brackets, where the number would go. The bracketed query is a subquery:

query.sql (ledger.db holds halls and gauges, as in lesson 06)

SELECT name, reading FROM gauges
WHERE reading > (SELECT AVG(reading) FROM gauges)
ORDER BY reading DESC;

Terminal: sqlite3 ledger.db < query.sql

╭─────────┬─────────╮
│  name   │ reading │
╞═════════╪═════════╡
│ fan     │  1200.0 │
│ bell    │   440.0 │
│ compass │   270.0 │
╰─────────┴─────────╯

Read it aloud: "the name and reading of the gauges whose reading is greater than the average reading." SQLite answered the inner query first, 263.1125, and then compared every row with it. If a reading changes tomorrow, the average changes with it, and the query stays right; a number copied by hand would not.

Why the brackets, and why not AVG in WHERE

The brackets are required. Without them, SQLite reaches a second SELECT where it expects a value:

query.sql (ledger.db holds halls and gauges, as in lesson 06)

SELECT name FROM gauges WHERE reading > SELECT AVG(reading) FROM gauges;

Terminal: sqlite3 ledger.db < query.sql

Parse error near line 1: near "SELECT": syntax error
  SELECT name FROM gauges WHERE reading > SELECT AVG(reading) FROM gauges;
                            error here ---^

And lesson 04's rule still holds: an aggregate cannot sit in WHERE on its own, as WHERE looks at one row at a time:

query.sql (ledger.db holds halls and gauges, as in lesson 06)

SELECT name FROM gauges WHERE reading > AVG(reading);

Terminal: sqlite3 ledger.db < query.sql

Parse error near line 1: misuse of aggregate function AVG()
  SELECT name FROM gauges WHERE reading > AVG(reading);
                            error here ---^

The subquery is exactly the way round that rule: the inner query works out the aggregate over all the rows, and hands WHERE one plain number.

Whose value is the largest?

Lesson 04 asked whose reading is the largest, and answered with ORDER BY and LIMIT, or with SQLite's own shortcut. A subquery gives a third way, which works in every database: find the largest value, then the rows that have it.

query.sql (ledger.db holds halls and gauges, as in lesson 06)

SELECT name, reading FROM gauges WHERE reading = (SELECT MAX(reading) FROM gauges);

Terminal: sqlite3 ledger.db < query.sql

╭──────┬─────────╮
│ name │ reading │
╞══════╪═════════╡
│ fan  │  1200.0 │
╰──────┴─────────╯

Unlike LIMIT 1, this keeps every row that ties for the largest value, if there are several.

A subquery in the SELECT list

A one-value subquery can sit anywhere a value can, the SELECT list included. How far is each Clock Tower gauge from the average?

query.sql (ledger.db holds halls and gauges, as in lesson 06)

SELECT name, reading, ROUND(reading - (SELECT AVG(reading) FROM gauges), 1) AS above_average
FROM gauges WHERE hall_id = 2;

Terminal: sqlite3 ledger.db < query.sql

╭──────────┬─────────┬───────────────╮
│   name   │ reading │ above_average │
╞══════════╪═════════╪═══════════════╡
│ pendulum │     2.0 │        -261.1 │
│ bell     │   440.0 │         176.9 │
╰──────────┴─────────┴───────────────╯

The pendulum is 261.1 below the average, so its number is negative; the bell is 176.9 above.

When the inner query gives more than one row

A subquery used as a value should give exactly one row. If it gives several, SQLite does not complain: it quietly uses the first row. The Clock Tower has two gauges, but only one name comes back:

query.sql (ledger.db holds halls and gauges, as in lesson 06)

SELECT (SELECT name FROM gauges WHERE hall_id = 2) AS name;

Terminal: sqlite3 ledger.db < query.sql

╭──────────╮
│   name   │
╞══════════╡
│ pendulum │
╰──────────╯

PostgreSQL refuses such a query with an error instead. When an inner query can give several rows, the question usually wants IN, the next section's tool.

Worked example 1

Which gauges read more than twice the average reading?

What we have: The average of the eight known readings is 263.1125, from the subquery SELECT AVG(reading) FROM gauges.

What we need: The gauges whose reading is greater than twice that average.

The plan: Put the average's subquery in brackets, multiply it by 2, and compare each reading with the result.

  1. The inner value: (SELECT AVG(reading) FROM gauges).
  2. Twice it, as part of the comparison: reading > 2 * (SELECT AVG(reading) FROM gauges).

query.sql (ledger.db holds halls and gauges, as in lesson 06)

SELECT name, reading FROM gauges WHERE reading > 2 * (SELECT AVG(reading) FROM gauges);

Terminal: sqlite3 ledger.db < query.sql

╭──────┬─────────╮
│ name │ reading │
╞══════╪═════════╡
│ fan  │  1200.0 │
╰──────┴─────────╯

Only the fan, at 1200.0.

Check: By hand: twice 263.1125 is 526.225; the fan's 1200.0 is above it, and the bell's 440.0 is not.

A path that fails: Writing reading > 2 * AVG(reading) with no subquery. WHERE cannot use an aggregate, and SQLite stops with misuse of aggregate function AVG().

Worked example 2

Which gauges stand in the same hall as the bell?

What we have: The bell's row holds its hall_id; every gauge has a hall_id.

What we need: The names of the gauges whose hall_id equals the bell's.

The plan: The inner query finds the bell's hall_id, one value; the outer query keeps the gauges with that hall_id.

  1. The inner value: (SELECT hall_id FROM gauges WHERE name = 'bell'), which gives 2.
  2. The outer test: WHERE hall_id = (...).

query.sql (ledger.db holds halls and gauges, as in lesson 06)

SELECT name FROM gauges WHERE hall_id = (SELECT hall_id FROM gauges WHERE name = 'bell');

Terminal: sqlite3 ledger.db < query.sql

╭──────────╮
│   name   │
╞══════════╡
│ pendulum │
│ bell     │
╰──────────╯

The pendulum and the bell itself, both in hall 2, the Clock Tower.

Check: The names are unique, so the inner query gives exactly one row: no first-row trap here. The bell is in its own answer, as it shares its own hall.

A path that fails: Writing WHERE hall_id = 'bell', comparing a hall number with a name. No hall_id equals the text bell, so the answer is empty, with no error.

When you are stuck: one-value subqueries

Run the inner query on its own first: the number it prints is exactly what the outer query uses.

If a one-value subquery seems to ignore rows, it may give several rows; SQLite uses the first. Use IN for a list.

A common mistake

Copying a number from one query into another by hand. When the data changes, the copied number goes stale; a subquery is worked out again every time.

Your turn

Write a query for the gauges whose reading is below the average.Tap to reveal
  1. The same subquery, with < in place of >.

SELECT name FROM gauges WHERE reading < (SELECT AVG(reading) FROM gauges); gives the boiler, pump, pendulum, kettle and valve.

Why does reading > (SELECT AVG(reading) FROM gauges) work when reading > AVG(reading) does not?Tap to reveal
  1. Which part works over all rows?

The subquery works out the average over all rows first and hands WHERE one number; AVG alone in WHERE is a misuse of aggregate.

What does SQLite do with a one-value subquery that returns three rows?Tap to reveal
  1. No error.

It uses the first row and ignores the rest; PostgreSQL would report an error.

Did you know?

The first row, or NULL

SQLite's documentation says the value of a subquery used as a value is the first row of the inner query's result, and NULL if the inner query returns no rows. So a subquery that finds nothing does not fail: it hands the outer query a NULL, and any comparison with it is not known.

Why it fits here: It answers the topic's question: no rows gives NULL, and several rows give the first.

Source: SQLite: SQL Language Expressions

PostgreSQL says no

Where SQLite quietly takes the first row, PostgreSQL stops. Its documentation says it is an error to use a query that returns more than one row or more than one column as a scalar subquery. Like SQLite, it lets a subquery that returns no rows through, and takes the result to be null.

Why it fits here: It shows two databases parting ways on this topic's first-row rule, which is why IN is the safe choice for a list.

Source: PostgreSQL: Value Expressions

In one line

A subquery in brackets can stand for one value, such as (SELECT AVG(reading) FROM gauges), in WHERE or SELECT; SQLite works it out first, and uses only its first row if it gives several.

A list from a query: IN

At a glance

IN with a subquery keeps the rows whose value is in another query's answer, a list made by SQL instead of by hand.

The gauges in halls kept by one keeper, the halls that hold a gauge above 100: each is an IN. A join can often answer the same question; IN reads closer to it when only one table's columns are wanted. NOT IN keeps the values not in the list. But a single NULL in that list makes every test not known, and then nothing at all is kept.

Take a guess: Does every database accept an empty list, as in x IN (), or only some?

Lesson 02's IN kept a value found in a list written by hand, such as unit IN ('C', 'bar'). The list can also come from a subquery. Which gauges does Hakim Verge look after? The keeper is in halls and the gauges in gauges, so ask halls for the ids, and keep the gauges whose hall_id is in that list:

query.sql (ledger.db holds halls and gauges, as in lesson 06)

SELECT name FROM gauges
WHERE hall_id IN (SELECT id FROM halls WHERE keeper LIKE 'Hakim%');

Terminal: sqlite3 ledger.db < query.sql

╭──────────╮
│   name   │
╞══════════╡
│ pendulum │
│ bell     │
╰──────────╯

The inner query gives a list with one id, 2; the outer query keeps the gauges whose hall_id is in it. Lesson 05 answered the same question with a join, and the answer is the same:

query.sql (ledger.db holds halls and gauges, as in lesson 06)

SELECT g.name FROM gauges g JOIN halls h ON g.hall_id = h.id WHERE h.keeper LIKE 'Hakim%';

Terminal: sqlite3 ledger.db < query.sql

╭──────────╮
│   name   │
╞══════════╡
│ pendulum │
│ bell     │
╰──────────╯

Which to choose? When the answer only needs columns of one table, IN often reads more like the question: "gauges whose hall is one of these". When the answer needs columns of both tables, such as each gauge with its keeper, a join is the tool.

The NOT IN trap

NOT IN keeps a value that is not in the list. So which halls have no gauges? The halls whose id is not among the gauges' hall_ids, surely:

query.sql (ledger.db holds halls and gauges, as in lesson 06)

SELECT name FROM halls WHERE id NOT IN (SELECT hall_id FROM gauges);

Terminal: sqlite3 ledger.db < query.sql

╭──────╮
│ name │
╘══════╛

An empty answer, though the Archive has no gauges. The cause is the compass. Its hall_id is NULL, so the inner list holds 1, 3, 2, NULL and the rest. For the Archive, SQLite must decide whether 4 NOT IN that list is true. 4 differs from 1, 2 and 3, but is 4 different from NULL? Not known. So the whole test is not known, never true, and WHERE drops the Archive. One NULL in a NOT IN list empties the answer, every time.

The cure is to keep NULL out of the list:

query.sql (ledger.db holds halls and gauges, as in lesson 06)

SELECT name FROM halls
WHERE id NOT IN (SELECT hall_id FROM gauges WHERE hall_id IS NOT NULL);

Terminal: sqlite3 ledger.db < query.sql

╭─────────╮
│  name   │
╞═════════╡
│ Archive │
╰─────────╯

The next section's NOT EXISTS gives the same answer without needing the cure at all, which is why many people prefer it for "which have none".

You writeIt keeps
x IN (SELECT ...)rows whose x is in the inner query's answer
x NOT IN (SELECT ...)rows whose x is not in it, but nothing at all if the answer holds a NULL
x NOT IN (SELECT y ... WHERE y IS NOT NULL)the rows meant, with NULL kept out

Worked example 3

Which keepers have at least one gauge reading above 100? Sort their names.

What we have: Keepers are in halls; readings are in gauges; hall_id links them.

What we need: The keepers whose hall holds a gauge above 100, each once, sorted.

The plan: The inner query lists the hall_ids of the gauges above 100; the outer query keeps the halls whose id is in that list.

  1. The inner list: SELECT hall_id FROM gauges WHERE reading > 100, which gives 1, 2 and the compass's NULL.
  2. The outer query: SELECT keeper FROM halls WHERE id IN (...), then ORDER BY keeper.

query.sql (ledger.db holds halls and gauges, as in lesson 06)

SELECT keeper FROM halls
WHERE id IN (SELECT hall_id FROM gauges WHERE reading > 100)
ORDER BY keeper;

Terminal: sqlite3 ledger.db < query.sql

╭─────────────╮
│   keeper    │
╞═════════════╡
│ Hakim Verge │
│ Ines Tappet │
╰─────────────╯

Hakim Verge and Ines Tappet.

Check: The fan (1200.0) is in the Engine Hall and the bell (440.0) in the Clock Tower. The compass (270.0) has no hall, and its NULL in the list does no harm to IN: a NULL only spoils NOT IN.

A path that fails: Writing it as a join without DISTINCT: SELECT h.keeper FROM halls h JOIN gauges g ON g.hall_id = h.id WHERE g.reading > 100. That works here, but a keeper with two such gauges would be listed twice; IN lists each hall once.

When you are stuck: IN with a subquery

Run the inner query alone and read its list: the outer query keeps exactly the values in it.

If NOT IN gives an empty answer that cannot be right, look for a NULL in the inner list, and add WHERE ... IS NOT NULL inside.

A common mistake

Trusting NOT IN with a column that can be NULL. A single NULL in the inner answer makes every NOT IN test not known, and nothing is kept.

Your turn

Write a query for the gauges that stand in a hall kept by Ines Tappet, using IN.Tap to reveal
  1. The inner query asks halls for the id.

SELECT name FROM gauges WHERE hall_id IN (SELECT id FROM halls WHERE keeper = 'Ines Tappet'); gives the boiler, pump, fan and valve.

Why does id NOT IN (SELECT hall_id FROM gauges) give nothing here?Tap to reveal
  1. The compass.

The list holds the compass's NULL, so every NOT IN test is not known, never true.

Does a NULL in the list spoil IN as well?Tap to reveal
  1. IN needs one match.

No: IN is true as soon as one value matches, so a NULL in the list does no harm to IN, only to NOT IN.

Did you know?

The NOT IN rule, in writing

The trap of this topic is the standard's own rule, not a bug. PostgreSQL's documentation states it. When no value on the right is equal and at least one right-hand row is null, NOT IN gives null, not true. It adds that this follows SQL's normal rules for combining nulls, the same rules lesson 02 met with AND and OR.

Why it fits here: It shows that the NOT IN trap is the SQL standard at work, the same in PostgreSQL as in SQLite.

Source: PostgreSQL: Subquery Expressions

An empty list is allowed in SQLite

SQLite lets the list after IN or NOT IN be empty, as in x IN (), and the test is then false for IN. Its documentation notes that most other engines require at least one element. So does the SQL92 standard. Generated queries, built by a program from a list that turns out empty, benefit most.

Why it fits here: It answers the topic's question: SQLite accepts an empty IN list, while the standard and most engines do not.

Source: SQLite: SQL Language Expressions

In one line

x IN (SELECT ...) keeps the rows whose x is in another query's answer; NOT IN gives nothing at all when that answer holds a NULL, so keep NULL out with IS NOT NULL, or use NOT EXISTS.

Is there any? EXISTS

At a glance

EXISTS asks one thing about a subquery: did it find any row at all?

It is true when the inner query finds at least one row, and false when it finds none. The inner query is usually linked to the outer row, such as g.hall_id = h.id. NOT EXISTS finds the rows with no match, and, unlike NOT IN, a NULL cannot spoil it, because EXISTS never answers not known. What the inner query selects does not matter, so people write SELECT 1.

Take a guess: Can EXISTS ever give NULL, as a comparison with NULL does?

Some questions only ask whether a match exists, not what it is. Does this hall have any gauge at all? EXISTS, followed by a subquery in brackets, is true when the subquery gives at least one row, and false when it gives none:

query.sql (ledger.db holds halls and gauges, as in lesson 06)

SELECT h.name FROM halls h
WHERE EXISTS (SELECT 1 FROM gauges g WHERE g.hall_id = h.id)
ORDER BY h.name;

Terminal: sqlite3 ledger.db < query.sql

╭────────────────╮
│      name      │
╞════════════════╡
│ Clock Tower    │
│ Couriers' Yard │
│ Engine Hall    │
╰────────────────╯

Read it aloud: "the names of the halls for which there exists a gauge whose hall_id is this hall's id." Notice h.id inside the brackets: the inner query looks out at the outer row. For each hall, SQLite runs the inner query with that hall's id and asks one thing: did it find a row? The Archive found none, so it was left out.

The SELECT 1 inside is a habit, not a rule. EXISTS never looks at what the inner query selects, only at whether it found a row, so people write 1, or *, to show that nothing is being read.

NOT EXISTS: which have none

NOT EXISTS turns the test round, and answers the question that NOT IN got wrong:

query.sql (ledger.db holds halls and gauges, as in lesson 06)

SELECT h.name FROM halls h
WHERE NOT EXISTS (SELECT 1 FROM gauges g WHERE g.hall_id = h.id);

Terminal: sqlite3 ledger.db < query.sql

╭─────────╮
│  name   │
╞═════════╡
│ Archive │
╰─────────╯

The Archive, as it should be. The compass's NULL does no harm here: for the Archive, the inner query asks for gauges whose hall_id equals 4, finds none, and NOT EXISTS is plainly true. EXISTS only ever answers true or false, never not known, so NULL cannot spoil it.

QuestionWith a subqueryLesson 05's way
Halls with gaugesWHERE EXISTS (SELECT 1 FROM gauges g WHERE g.hall_id = h.id)JOIN, with DISTINCT
Halls with noneWHERE NOT EXISTS (...)LEFT JOIN ... WHERE g.id IS NULL
Halls with none, the risky wayWHERE id NOT IN (SELECT hall_id FROM gauges)fails when a hall_id is NULL

Worked example 4

Which halls have no gauges? Answer with NOT EXISTS, and compare it with NOT IN.

What we have: Four halls; the gauges' hall_ids include the compass's NULL.

What we need: The halls that no gauge points at.

The plan: For each hall, ask whether a gauge with its id exists, and keep the halls for which none does.

  1. The inner query, for one hall: SELECT 1 FROM gauges g WHERE g.hall_id = h.id.
  2. Keep the halls where it finds nothing: WHERE NOT EXISTS (...).

query.sql (ledger.db holds halls and gauges, as in lesson 06)

SELECT h.name FROM halls h
WHERE NOT EXISTS (SELECT 1 FROM gauges g WHERE g.hall_id = h.id);

Terminal: sqlite3 ledger.db < query.sql

╭─────────╮
│  name   │
╞═════════╡
│ Archive │
╰─────────╯
  1. And the NOT IN version, for comparison:

query.sql (ledger.db holds halls and gauges, as in lesson 06)

SELECT name FROM halls WHERE id NOT IN (SELECT hall_id FROM gauges);

Terminal: sqlite3 ledger.db < query.sql

╭──────╮
│ name │
╘══════╛

The Archive, which NOT EXISTS finds and NOT IN misses.

Check: The halls' ids are 1 to 4, and the gauges use 1, 2 and 3: only 4, the Archive, is unused.

A path that fails: Forgetting the link inside the brackets: WHERE NOT EXISTS (SELECT 1 FROM gauges). Without g.hall_id = h.id, the inner query finds gauges for every hall, so NOT EXISTS is false everywhere, and the answer is empty.

When you are stuck: EXISTS

Check the link inside the brackets: the inner WHERE must mention the outer row, as g.hall_id = h.id does, or every row gets the same answer.

For "which have none", prefer NOT EXISTS to NOT IN when the inner column can be NULL.

A common mistake

Expecting EXISTS to return the matching rows. It only answers true or false for each outer row; the outer SELECT decides what is shown.

Your turn

Write a query for the halls that have a gauge reading above 100, with EXISTS.Tap to reveal
  1. Add the reading test inside the brackets.

SELECT h.name FROM halls h WHERE EXISTS (SELECT 1 FROM gauges g WHERE g.hall_id = h.id AND g.reading > 100); gives the Engine Hall and the Clock Tower.

Why does NOT EXISTS give the Archive when NOT IN gives nothing?Tap to reveal
  1. Can EXISTS be not known?

EXISTS only answers true or false, so the compass's NULL cannot make it not known, as it does with NOT IN.

Does it matter whether you write SELECT 1 or SELECT * inside EXISTS?Tap to reveal
  1. What does EXISTS look at?

No: EXISTS only asks whether a row was found, never what it holds.

Did you know?

Only 0 or 1

SQLite's documentation says the EXISTS operator always evaluates to one of the integer values 0 and 1: 1 if the inner query would return one or more rows, 0 if it would return none. It never gives NULL, which is exactly why NOT EXISTS keeps working where NOT IN breaks.

Why it fits here: It answers the topic's question: EXISTS is always 0 or 1, never NULL.

Source: SQLite: SQL Language Expressions

SELECT 1 or SELECT *, it does not matter

The habit of writing SELECT 1 inside EXISTS has a reason in the documentation. SQLite's says that the number of columns the inner query returns, and the values in them, have no effect on the result of EXISTS. It adds that rows containing NULL values are not handled any differently from rows without them.

Why it fits here: It explains this topic's SELECT 1: EXISTS reads whether a row exists, never what it holds.

Source: SQLite: SQL Language Expressions

In one line

EXISTS (subquery) is true when the subquery finds at least one row, usually linked to the outer row; NOT EXISTS finds the rows with no match, and, unlike NOT IN, a NULL cannot spoil it.

A subquery that looks outward

At a glance

A correlated subquery mentions the outer query's row, so SQLite works it out again for each row, with that row's values.

Which gauges read above the average of their own hall? For each gauge, the inner query averages the gauges of the same hall. The same table appears inside and out, so each copy gets its own short name, such as g and g2. It reads like the question, but on a big table it can be slow, as it runs once per row.

Take a guess: Does SQLite work out an ordinary, uncorrelated subquery once, or again for every row?

The EXISTS section's inner query mentioned h.id, a column of the outer row. A subquery that does that is called correlated: it cannot be answered once for the whole query, so SQLite answers it again for every outer row, with that row's values. Here is the opening scene's hardest question: which gauges read above the average of their own hall?

query.sql (ledger.db holds halls and gauges, as in lesson 06)

SELECT g.name, g.reading FROM gauges g
WHERE g.reading > (SELECT AVG(g2.reading) FROM gauges g2 WHERE g2.hall_id = g.hall_id)
ORDER BY g.name;

Terminal: sqlite3 ledger.db < query.sql

╭──────┬─────────╮
│ name │ reading │
╞══════╪═════════╡
│ bell │   440.0 │
│ fan  │  1200.0 │
╰──────┴─────────╯

The same table appears twice, so each copy needs its own short name: g for the gauge being tested, g2 for the gauges being averaged. For the fan, the inner query averages the gauges whose hall_id is the fan's, 1: (96.5 + 4.2 + 1200.0 + 4.2) ÷ 4 = 326.225, and 1200.0 is above it. For the bell, it averages hall 2: (2.0 + 440.0) ÷ 2 = 221.0, and 440.0 is above it. The kettle equals its hall's average, 88.0, so it is not above it.

Picture it as the loop inside a loop of lesson 05: for each gauge g, loop over the gauges g2 of the same hall. The compass has no hall, so its inner average is of no rows, NULL, and the comparison is not known; it is left out.

A correlated subquery in SELECT

The same idea gives a count per hall, one hall at a time, with the Archive's 0 included:

query.sql (ledger.db holds halls and gauges, as in lesson 06)

SELECT h.name, (SELECT COUNT(*) FROM gauges g WHERE g.hall_id = h.id) AS gauges
FROM halls h ORDER BY h.id;

Terminal: sqlite3 ledger.db < query.sql

╭────────────────┬────────╮
│      name      │ gauges │
╞════════════════╪════════╡
│ Engine Hall    │      4 │
│ Clock Tower    │      2 │
│ Couriers' Yard │      2 │
│ Archive        │      0 │
╰────────────────┴────────╯

Lesson 05 got these numbers with a LEFT JOIN, GROUP BY and COUNT(g.id). Both are right. The subquery reads like the question, "for each hall, how many gauges", and cannot fall into lesson 05's COUNT(*) trap: a hall with no gauges gives a count of 0 by itself.

An ordinary subqueryA correlated subquery
Mentions the outer rownoyes, such as g.hall_id or h.id
Worked outonce, for the whole queryagain for each outer row
Example(SELECT AVG(reading) FROM gauges)(SELECT AVG(g2.reading) FROM gauges g2 WHERE g2.hall_id = g.hall_id)

Worked example 5

Which gauges read above the average of their own hall? Sort them by name.

What we have: Each gauge's hall is its hall_id; the readings of a hall can be averaged with AVG.

What we need: The gauges whose reading is greater than their hall's average reading.

The plan: A correlated subquery: for each gauge g, average the gauges g2 with the same hall_id, and compare.

  1. Two names for one table: gauges g outside, gauges g2 inside.
  2. The link: WHERE g2.hall_id = g.hall_id, so each gauge gets its own hall's average.
  3. The test: g.reading > (SELECT AVG(g2.reading) ...).

query.sql (ledger.db holds halls and gauges, as in lesson 06)

SELECT g.name, g.reading FROM gauges g
WHERE g.reading > (SELECT AVG(g2.reading) FROM gauges g2 WHERE g2.hall_id = g.hall_id)
ORDER BY g.name;

Terminal: sqlite3 ledger.db < query.sql

╭──────┬─────────╮
│ name │ reading │
╞══════╪═════════╡
│ bell │   440.0 │
│ fan  │  1200.0 │
╰──────┴─────────╯

The bell and the fan.

Check: Hall averages: the Engine Hall 326.225 (only the fan is above), the Clock Tower 221.0 (only the bell is above), the Couriers' Yard 88.0 (the kettle equals it, the chimney is NULL).

A path that fails: Leaving out the link, as in (SELECT AVG(g2.reading) FROM gauges g2). That is the works' average, 263.1125, the same for everyone, and the answer becomes the fan, the bell and the compass.

When you are stuck: correlated subqueries

Pick one outer row, such as the fan, and work the inner query out by hand with its values: that is exactly what SQLite does for every row.

If both copies of a table have no short names, SQLite cannot tell them apart; name them, such as g and g2.

A common mistake

Forgetting that a correlated subquery runs once per outer row. On a large table that can be slow; a join or a GROUP BY often gives the same answer faster.

Your turn

Write a query that shows each gauge's name with the number of gauges in its hall.Tap to reveal
  1. A correlated COUNT in the SELECT list.

SELECT g.name, (SELECT COUNT(*) FROM gauges g2 WHERE g2.hall_id = g.hall_id) FROM gauges g; gives the boiler 4, the pendulum 2, and the compass 0.

What makes a subquery correlated?Tap to reveal
  1. Look inside the brackets.

It mentions a column of the outer query's row, so it is worked out again for each outer row.

Why is the compass not in the answer of the worked example?Tap to reveal
  1. Its hall_id is NULL.

No gauge has a hall_id equal to NULL, so its inner average is NULL, and a comparison with NULL is not known.

Did you know?

Once, or every time

SQLite's documentation draws the line exactly. A subquery that refers to columns of the outer query is known as a correlated subquery, and it is reevaluated each time its result is required. An uncorrelated subquery is evaluated only once, and its result is reused as necessary, so the average of the whole works is worked out a single time.

Why it fits here: It answers the topic's question, and gives the reason a correlated subquery can be slow.

Source: SQLite: SQL Language Expressions

Outer values held still

PostgreSQL's documentation explains how a subquery sees the outer row. It says the subquery can refer to variables from the surrounding query, and these act as constants during any one evaluation of the subquery. So for the fan, g.hall_id is just 1 while the inner average is worked out. For the bell it is 2.

Why it fits here: It shows what the link of this topic's correlated subquery means: the outer value is fixed during each inner run.

Source: PostgreSQL: Value Expressions

In one line

A correlated subquery mentions the outer row, such as g.hall_id, so SQLite works it out again for each row; use two short names when the same table is inside and out.

Queries built on queries: FROM and WITH

At a glance

Every answer is a table, so a subquery in FROM can be queried again, and WITH gives that subquery a name first.

A table of totals per hall, made by GROUP BY, can be averaged by an outer query: an aggregate of an aggregate. WITH names each step, so a long query reads top to bottom like a recipe, each named part runnable alone. WITH RECURSIVE builds rows one from the last, a starting row and a step that stops, which walks trees and counts.

Take a guess: What surprising puzzles does SQLite's own documentation solve with a recursive WITH?

Every answer is a table, so a query's answer can be queried again. A subquery in FROM is treated as a table. Here is a small table of totals, one row per hall, made by a GROUP BY and then read by an outer query:

query.sql (ledger.db holds halls and gauges, as in lesson 06)

SELECT * FROM (
  SELECT hall_id, SUM(reading) AS total FROM gauges WHERE hall_id IS NOT NULL GROUP BY hall_id
) ORDER BY total DESC;

Terminal: sqlite3 ledger.db < query.sql

╭─────────┬────────╮
│ hall_id │ total  │
╞═════════╪════════╡
│       1 │ 1304.9 │
│       2 │  442.0 │
│       3 │   88.0 │
╰─────────┴────────╯

Now a question about those totals: what is the average hall total? An aggregate of an aggregate needs exactly this, a table of totals first, then an AVG over it:

query.sql (ledger.db holds halls and gauges, as in lesson 06)

SELECT ROUND(AVG(total), 1) AS average_total FROM (
  SELECT hall_id, SUM(reading) AS total FROM gauges WHERE hall_id IS NOT NULL GROUP BY hall_id
);

Terminal: sqlite3 ledger.db < query.sql

╭───────────────╮
│ average_total │
╞═══════════════╡
│         611.6 │
╰───────────────╯

(1304.9 + 442.0 + 88.0) ÷ 3 = 611.63..., rounded to 611.6. Lesson 04's GROUP BY could give the totals, but not their average in the same step; a subquery in FROM can.

Naming a subquery: WITH

Subqueries inside subqueries grow hard to read. WITH lets you give a subquery a name first, and then use the name like a table. The named part is called a common table expression, or CTE:

query.sql (ledger.db holds halls and gauges, as in lesson 06)

WITH totals AS (
  SELECT hall_id, SUM(reading) AS total FROM gauges WHERE hall_id IS NOT NULL GROUP BY hall_id
)
SELECT h.name, t.total FROM totals t JOIN halls h ON h.id = t.hall_id
ORDER BY t.total DESC;

Terminal: sqlite3 ledger.db < query.sql

╭────────────────┬────────╮
│      name      │ total  │
╞════════════════╪════════╡
│ Engine Hall    │ 1304.9 │
│ Clock Tower    │  442.0 │
│ Couriers' Yard │   88.0 │
╰────────────────┴────────╯

Read it from the top, like a recipe: first make the totals, then join them to the halls for their names. The name totals lasts only for this one statement. A WITH can hold several named parts, separated by commas, each able to use the ones before it.

A WITH that calls itself

One kind of WITH, written WITH RECURSIVE, may use its own name inside itself, the way a JavaScript function can call itself. Here it counts from 1 to 5: it starts with 1, and keeps adding a row with x + 1 while x is below 5:

query.sql (ledger.db holds halls and gauges, as in lesson 06)

WITH RECURSIVE n(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM n WHERE x < 5)
SELECT x FROM n;

Terminal: sqlite3 ledger.db < query.sql

╭───╮
│ x │
╞═══╡
│ 1 │
│ 2 │
│ 3 │
│ 4 │
│ 5 │
╰───╯

Recursive queries walk family trees, folders inside folders and routes through a map; the PostgreSQL track meets them properly. For now, recognise the shape: a starting row, UNION ALL, and a step that stops.

You writeIt makes
SELECT ... FROM (SELECT ...)an inner answer used as a table
WITH totals AS (SELECT ...) SELECT ... FROM totalsthe same, with the inner query named first
WITH a AS (...), b AS (... FROM a ...)several named parts, each using the ones before
WITH RECURSIVE n(x) AS (start UNION ALL step)rows built one from the last, until the step stops

Worked example 6

Which hall has the largest total of readings? Name it, with WITH.

What we have: Readings per hall come from SUM with GROUP BY; the halls' names are in halls.

What we need: One row: the name and total of the hall with the largest total.

The plan: Name the totals with WITH, join them to halls for the names, sort by total, and keep one row.

  1. The named part: WITH totals AS (SELECT hall_id, SUM(reading) AS total FROM gauges WHERE hall_id IS NOT NULL GROUP BY hall_id).
  2. The names: JOIN halls h ON h.id = t.hall_id.
  3. The largest: ORDER BY t.total DESC LIMIT 1.

query.sql (ledger.db holds halls and gauges, as in lesson 06)

WITH totals AS (
  SELECT hall_id, SUM(reading) AS total FROM gauges WHERE hall_id IS NOT NULL GROUP BY hall_id
)
SELECT h.name, t.total FROM totals t JOIN halls h ON h.id = t.hall_id
ORDER BY t.total DESC LIMIT 1;

Terminal: sqlite3 ledger.db < query.sql

╭─────────────┬────────╮
│    name     │ total  │
╞═════════════╪════════╡
│ Engine Hall │ 1304.9 │
╰─────────────┴────────╯

The Engine Hall, with 1304.9.

Check: By hand: 96.5 + 4.2 + 1200.0 + 4.2 = 1304.9, far above the Clock Tower's 442.0 and the yard's 88.0.

A path that fails: Using the name totals in a second statement after the semicolon. A WITH's names last only for the one statement they belong to, and the second one stops with no such table: totals.

When you are stuck: FROM and WITH

Run the inner query, or the WITH part, alone first, and read the table it makes: the outer query reads exactly that.

If a query of totals counts a hall twice or not at all, check the GROUP BY inside, and whether NULLs were left out on purpose.

A common mistake

Writing an aggregate of an aggregate directly, such as AVG(SUM(reading)). SQLite refuses it; make the table of sums first, in FROM or WITH, and average that.

Your turn

Write a query for the largest hall total, using a subquery in FROM.Tap to reveal
  1. MAX over the table of totals.

SELECT MAX(total) FROM (SELECT hall_id, SUM(reading) AS total FROM gauges WHERE hall_id IS NOT NULL GROUP BY hall_id); gives 1304.9.

How long does a WITH's name last?Tap to reveal
  1. One statement.

Only for the statement it is written in; the next statement must write its own WITH.

What are the two parts of a WITH RECURSIVE, joined by UNION ALL?Tap to reveal
  1. Where it starts, and how it goes on.

A starting row, and a step that makes the next row from the last one until its WHERE stops it.

Did you know?

WITH arrived in 2014

Named subqueries are a younger part of SQLite than SELECT. Its list of changes adds support for common table expressions and the WITH clause in version 3.8.3, released on 2014-02-03. Before then, every step of a long question had to be nested inside the next, in brackets within brackets.

Why it fits here: It dates this topic's WITH, the tool that lets a long query read in named steps.

Source: SQLite: Release History

A Sudoku solved by one query

SQLite's page on WITH ends with what it calls outlandish recursive query examples. One computes an approximation of the Mandelbrot Set and prints it as ASCII-art, a picture made of characters. The next solves a Sudoku puzzle, read from an 81-character string with a full stop for each blank square, all with WITH RECURSIVE.

Why it fits here: It answers the topic's question, and shows how far this topic's starting row and repeated step can reach.

Source: SQLite: The WITH Clause

In one line

A subquery in FROM is used as a table, and WITH names it first so the query reads top to bottom; WITH RECURSIVE builds rows one from the last, until its step stops.

Where it is used

Subqueries answer the questions that start with "compared with" or "any" or "none".

Compared with the rest

A shop's report of products priced above the average, a class's list of marks above the class average, a list of employees earning more than their department's average: each is this lesson's one-value or correlated subquery. The average is worked out fresh every time, so the report never goes stale.

Any, and none

Customers who have placed at least one order use EXISTS; customers who have never ordered use NOT EXISTS. Shops send the second group a "we miss you" e-mail, and the NOT IN trap is a classic bug in exactly that list, whenever an order's customer column can be NULL.

Reports in steps

Analysts write long reports as a chain of WITH parts: first the sales per day, then the averages per week, then the weeks above the average. Each step has a name and can be run alone to check it, which makes a hundred-line query readable.

The questionThe tool
Products priced above the averageWHERE price > (SELECT AVG(price) FROM products)
Customers with an orderWHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id)
Customers with no orderWHERE NOT EXISTS (...), not NOT IN
Each department's best earnera correlated subquery on the department's MAX
A report in stepsWITH daily AS (...), weekly AS (...) SELECT ...

Mistakes and how to find them

Subqueries fail loudly when they are written wrong, and quietly when they answer a different question. This file holds four mistakes, two of each kind.

query.sql (ledger.db holds halls and gauges, as in lesson 06)

SELECT name FROM gauges WHERE reading > SELECT AVG(reading) FROM gauges;
SELECT name FROM gauges WHERE reading > AVG(reading);
SELECT name FROM halls WHERE id NOT IN (SELECT hall_id FROM gauges);
SELECT name FROM gauges WHERE reading = (SELECT reading FROM gauges WHERE hall_id = 2);

Terminal: sqlite3 ledger.db < query.sql

Parse error near line 1: near "SELECT": syntax error
  SELECT name FROM gauges WHERE reading > SELECT AVG(reading) FROM gauges;
                            error here ---^
Parse error near line 2: misuse of aggregate function AVG()
  SELECT name FROM gauges WHERE reading > AVG(reading);
                            error here ---^
╭──────╮
│ name │
╘══════╛
╭──────────╮
│   name   │
╞══════════╡
│ pendulum │
╰──────────╯

Line 1 forgot the brackets around the inner SELECT: a syntax error at the second SELECT. Line 2 put AVG straight into WHERE: a misuse of aggregate function, which a subquery would have avoided.

Lines 3 and 4 are the quiet ones. Line 3 is the NOT IN trap: the compass's NULL in the inner list makes every test not known, and the Archive, the real answer, vanishes into an empty table. Line 4 used = with an inner query that gives two readings, 2.0 and 440.0; SQLite quietly used the first, so only the pendulum came back and the bell went missing. IN was meant.

The quiet mistakes

The queryWhat it really doesWhat was meant
id NOT IN (SELECT hall_id FROM gauges)nothing at all, as the list holds a NULLNOT EXISTS, or IS NOT NULL inside
reading = (SELECT reading ... several rows)compares with the first row onlyreading IN (SELECT ...)
EXISTS (SELECT 1 FROM gauges) with no linkthe same answer for every outer rowlink it: WHERE g.hall_id = h.id
(SELECT AVG(reading) FROM gauges g2) with no linkthe works' average, not the hall'sWHERE g2.hall_id = g.hall_id
WITH t AS (...) used in a later statementno such table: twrite the WITH again, or one statement

A way to check a subquery

  1. Run the inner query alone, and read its answer: one value, a list, or a table.
  2. For a list, look for NULL in it before you use NOT IN.
  3. For a correlated subquery, pick one outer row and work the inner query out by hand with its values.
  4. Run the outer query with the inner answer typed in by hand, and compare with the full query.
  5. If a join would answer the same question, write it too: two ways that agree are a strong check.

The debugging corner: show the inner answer beside each row

Put the subquery in the SELECT list to see what each row is compared with, such as SELECT name, reading, (SELECT AVG(g2.reading) FROM gauges g2 WHERE g2.hall_id = g.hall_id) AS hall_average FROM gauges g;. Every row then shows the very number its test used.

Quick card

The whole lesson on one card. Come back to it whenever you need a reminder.

query.sql (ledger.db holds halls and gauges, as in lesson 06)

SELECT name, reading FROM gauges
WHERE reading > (SELECT AVG(reading) FROM gauges)
  AND hall_id IN (SELECT id FROM halls)
ORDER BY reading DESC;

Terminal: sqlite3 ledger.db < query.sql

╭──────┬─────────╮
│ name │ reading │
╞══════╪═════════╡
│ fan  │  1200.0 │
│ bell │   440.0 │
╰──────┴─────────╯
To do thisWrite this
Compare with a worked-out valueWHERE reading > (SELECT AVG(reading) FROM gauges)
The rows with the largest valueWHERE reading = (SELECT MAX(reading) FROM gauges)
Keep values found by another queryWHERE hall_id IN (SELECT id FROM halls WHERE ...)
Values not found, safelyNOT IN (SELECT ... WHERE x IS NOT NULL), or NOT EXISTS
Rows that have a matchWHERE EXISTS (SELECT 1 FROM gauges g WHERE g.hall_id = h.id)
Rows with no matchWHERE NOT EXISTS (...)
Compare with the row's own group(SELECT AVG(g2.reading) FROM gauges g2 WHERE g2.hall_id = g.hall_id)
Query an answer againSELECT ... FROM (SELECT ...)
Name a stepWITH totals AS (SELECT ...) SELECT ... FROM totals
Count up with a queryWITH RECURSIVE n(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM n WHERE x < 5)

Words to know: subquery, inner query, outer query, IN, NOT IN, EXISTS, NOT EXISTS, correlated subquery, common table expression, WITH, WITH RECURSIVE.

Self-check

Say each answer aloud before you open it.

What does SQLite do first with WHERE reading > (SELECT AVG(reading) FROM gauges)?Tap to reveal
  1. Inside out.

It works out the inner query, the average, and then compares every row with that one number.

Why can NOT IN give an empty answer that is wrong?Tap to reveal
  1. A NULL in the list.

If the inner list holds a NULL, every NOT IN test is not known, so no row is kept.

What does EXISTS look at in its subquery?Tap to reveal
  1. Not the values.

Only whether the subquery found at least one row.

What makes a subquery correlated, and what does that cost?Tap to reveal
  1. The outer row.

It mentions the outer row, so it is worked out again for each row, which can be slow on big tables.

Why name a subquery with WITH?Tap to reveal
  1. Reading order.

So that a long query reads top to bottom in named steps, each of which can be run and checked alone.

The story: The last page of the ledger

By evening no clerk writes a slip. The gauges above the average, the halls with no gauge, the gauges above their own hall's average: each is one question, with another question folded inside it.

The clerk who was confused by the compass's blank space has learned to ask whether a matching line exists, instead of whether a number is in a list, and the blank no longer matters.

The Registrar closes the ledger and hands over a heavy key. "You can keep a ledger now," she says. "Across the square is the Great Vault, where one great ledger is kept for the whole city, and many clerks write in it at once. That is where you go next."

Reagents gathered: subquery, IN, EXISTS, NOT EXISTS, WITH, AVG.

Sources