Subqueries and Nested Queries

Put one SELECT inside another with scalar subqueries, IN, EXISTS and correlated subqueries, and avoid the NOT IN and NULL trap.

By Kevin McAleer,    6 Minutes

Page last updated November 24, 2026


Course Cover Image


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"]

A subquery that returns one value

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

A subquery that returns a list: IN

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: is there at least one?

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

The NOT IN trap

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.

Subqueries in the SELECT list

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.

Subqueries in FROM

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

Try it Yourself

  1. List the readings that are above the overall average reading, highest first.
  2. Use IN with a subquery on builds to find the robots built by Sam. (You’ll need a second, nested subquery on builders.)
  3. Challenge: find sensors that cost more than the average for their own kind. Hint: a correlated subquery with WHERE kind = s.kind. Only the VL53L0X should appear.

Common Issues

  • Problem: NOT IN returns no rows, although I know there are matches.
  • Solution: Switch to 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.

  • Problem: My = (SELECT ...) subquery returns more than one row, but SQLite doesn’t complain and I only see one answer.
  • Solution: Use 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.

  • Problem: no such column when the subquery refers to the outer table.
  • Solution: Check that the outer table has an alias (like r) and you spelt it the same way inside.
  • Why: A correlated subquery finds the outer row through that alias.

Check your understanding

Quick quiz 1 of 3

What makes a subquery “correlated”?

Quick quiz 2 of 3

Why did NOT IN (SELECT robot_id FROM sensors) return nothing?

Quick quiz 3 of 3

When must a subquery in FROM be given an alias?

Now let’s make our favourite queries reusable, and make them fast.

< Previous Next >

Was this lesson helpful?

Course complete

Congratulations, you finished Getting Started with SQL!

That's all 16 lessons done. Let people know, it's a great way to inspire someone else to start.

Share card: I completed Getting Started with SQL on KevsRobots
Post Bluesky LinkedIn Facebook


What are you looking for?
Watch Videos Get Ideas Learn Something Read a Review Read the Blog Search
... Z Z z