Subqueries
A query inside a query: filter by a computed value, test existence and compare against a list.
A subquery is a SELECT written inside another statement. It lets you answer a question in two steps without creating a temporary table.
Three places a subquery can live
- In WHERE: compare with a single value or test membership in a list.
- In FROM: treat the result as a temporary table (it needs an alias).
- In SELECT: compute one value per row (a scalar subquery).
SELECT user_id, total
FROM orders
WHERE total > (SELECT AVG(total) FROM orders);SELECT name
FROM users
WHERE id IN (SELECT user_id FROM orders WHERE total > 100);EXISTS
EXISTS returns true when the subquery returns at least one row. It stops at the first match, so it is often the clearest way to ask "does a related row exist?".
SELECT u.name
FROM users u
WHERE EXISTS (
SELECT 1 FROM orders o WHERE o.user_id = u.id
);CarefulBe careful with NOT IN. If the subquery returns even one NULL, NOT IN matches no rows at all. Prefer NOT EXISTS, which does not have this trap.
NoteA subquery that refers to a column of the outer query (like o.user_id = u.id above) is a correlated subquery: conceptually it runs once per outer row.
Test yourself
Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.