appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

Subqueries

Lesson 1 of 410 minIntermediate

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).
Users who spent more than the average order
SELECT user_id, total
FROM orders
WHERE total > (SELECT AVG(total) FROM orders);
IN with a list produced by a query
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.

1. Which subquery position needs an alias?
2. Why is NOT EXISTS safer than NOT IN?
HintWHERE id IN (SELECT ...).

Key terms