By Kevin McAleer, 6 Minutes
Page last updated November 24, 2026

By the end of this lesson you will be able to write a query inside another query, choose between IN and EXISTS, and explain why NOT IN can silently return nothing.
Some questions need two steps: “which sensors cost more than the average sensor?” First find the average, then compare. A subquery lets you do both in one statement, by putting a SELECT in brackets inside another.
flowchart LR
A["Inner query runs: AVG(price) = 2.63"] --> B["Outer query uses the answer"]
B --> C["WHERE price > 2.63"]
C --> D["MPU6050, VL53L0X"]
SELECT model, price
FROM sensors
WHERE price > (SELECT AVG(price) FROM sensors)
ORDER BY price;
model price
------- -----
MPU6050 3.8
VL53L0X 6.0
The inner query gives a single number (about 2.63), and the outer query treats it like any other value. The same trick finds robots whose battery beats the average:
SELECT name, battery_mah
FROM robots
WHERE battery_mah > (SELECT AVG(battery_mah) FROM robots);
name battery_mah
----- -----------
Smars 2000
If the inner query returns a column of values, test against it with IN. Which robots carry a distance sensor?
SELECT name
FROM robots
WHERE robot_id IN (SELECT robot_id FROM sensors WHERE kind = 'distance')
ORDER BY name;
name
-----------
Pico Walker
Smars
You could write this as a join too. Subqueries often read more naturally when you only need to test for membership, and don’t need columns from the second table.
EXISTS asks “does the inner query find any row?” It is true or false, and doesn’t care what the row contains (so people write SELECT 1). Robots that have a line sensor:
SELECT name
FROM robots AS r
WHERE EXISTS (
SELECT 1 FROM sensors AS s
WHERE s.robot_id = r.robot_id AND s.kind = 'line'
)
ORDER BY name;
name
-----------
Line Chaser
Smars
Notice the inner query mentions r.robot_id from the outer query. That makes it a correlated subquery: it is re-run for each robot in turn, with that robot’s ID filled in. Put NOT in front, and you find robots with no sensors at all:
SELECT name
FROM robots AS r
WHERE NOT EXISTS (SELECT 1 FROM sensors AS s WHERE s.robot_id = r.robot_id)
ORDER BY name;
name
-----------
Arm Buddy
Mystery Bot
It’s tempting to write the same question with NOT IN:
SELECT name FROM robots
WHERE robot_id NOT IN (SELECT robot_id FROM sensors);
name
----
Nothing came back, even though Arm Buddy and Mystery Bot clearly have no sensors. The culprit is our spare VL53L0X, whose robot_id is NULL. The list contains an unknown value, so “is robot 3 not in the list?” can never be answered with a firm yes. Either filter the NULL out:
SELECT name FROM robots
WHERE robot_id NOT IN (SELECT robot_id FROM sensors WHERE robot_id IS NOT NULL)
ORDER BY name;
or use NOT EXISTS, which has no such problem. Prefer NOT EXISTS.
A single-value subquery can sit in the column list. This counts each robot’s sensors, one robot at a time:
SELECT name,
(SELECT COUNT(*) FROM sensors AS s WHERE s.robot_id = r.robot_id) AS sensor_count
FROM robots AS r
ORDER BY name;
name sensor_count
----------- ------------
Arm Buddy 0
Line Chaser 2
Mystery Bot 0
Pico Walker 2
Smars 2
A LEFT JOIN with GROUP BY (lesson 9) gives the same answer, often faster on big tables.
You can also treat a query’s result as a temporary table, as long as you give it an alias. Which kinds of sensor cost more than 2 on average?
SELECT kind, ROUND(avg_price, 2) AS avg_price
FROM (
SELECT kind, AVG(price) AS avg_price
FROM sensors
GROUP BY kind
) AS per_kind
WHERE avg_price > 2
ORDER BY kind;
kind avg_price
-------- ---------
distance 3.67
motion 3.8
IN with a subquery on builds to find the robots built by Sam. (You’ll need a second, nested subquery on builders.)WHERE kind = s.kind. Only the VL53L0X should appear.NOT IN returns no rows, although I know there are matches.NOT EXISTS, or add WHERE column IS NOT NULL inside the subquery.Why: If the list contains NULL, the comparison is unknown for every row.
= (SELECT ...) subquery returns more than one row, but SQLite doesn’t complain and I only see one answer.IN when the inner query can return several rows.Why: SQLite quietly uses the first row of the inner query. MySQL and PostgreSQL stop with an error, which is the safer behaviour.
no such column when the subquery refers to the outer table.r) and you spelt it the same way inside.Quick quiz 1 of 3
What makes a subquery “correlated”?
EXISTS example, s.robot_id = r.robot_id links the inner query to the current outer robot.Quick quiz 2 of 3
Why did NOT IN (SELECT robot_id FROM sensors) return nothing?
NULL robot. NOT EXISTS avoids the problem.Quick quiz 3 of 3
When must a subquery in FROM be given an alias?
per_kind above.Now let’s make our favourite queries reusable, and make them fast.
Comments