Subquery
Подзапрос
A SQL query nested inside another SQL statement. The surrounding statement can use it to get a value, work with a set of rows, or check whether any matching row exists.
Also known as: вложенный запрос
What a subquery does
Suppose you want to list products priced above the catalog average. You could fetch the average in one statement and pass it into a second, but SQL can express both steps together: put SELECT AVG(price) FROM products in parentheses on the right-hand side of price >. That inner SELECT is a subquery. Here it supplies a number; elsewhere it might supply a table or simply answer whether a match exists.
What the outer query expects
- A single value: A scalar subquery returns one column and at most one row. You can use it in an expression, such as a comparison or a column in the
SELECTlist. No rows meansNULL; more than one row is an error. - Values to match against: In
id IN (SELECT customer_id FROM orders), the inner query can return many rows, andINtests whether the ID matches one of the returned values. - A yes-or-no existence check:
EXISTSis true if its subquery returns at least one row. It does not matter what values that row contains. - A source of rows: A subquery in
FROMis a derived table. For example, you can group orders by customer inside it, then join those totals to customer details in the outer query.
Example: find customers who have never ordered
SELECT c.id, c.name
FROM customers AS c
WHERE NOT EXISTS (
SELECT 1
FROM orders AS o
WHERE o.customer_id = c.id
);
The inner query refers to c.id from the outer query. That makes it a correlated subquery: the answer can differ from one customer to the next. SELECT 1 is conventional here because EXISTS only checks whether a row was returned. The catalog-average query, by contrast, is uncorrelated: it doesn't need a value from the current product row.
Common pitfalls and interview questions
If you're asked to rewrite the example with NOT IN, first check whether orders.customer_id can be NULL. If the subquery returns a NULL and no value matches the current ID, the NOT IN condition evaluates to unknown, not true. A WHERE clause keeps only rows for which the condition is true. The equality test inside NOT EXISTS instead treats a row with a NULL customer ID as no match.
Another common exercise is to list customers who have ordered. EXISTS keeps each qualifying customer row once, while an INNER JOIN produces one row per matching order. Explain which output you want before comparing performance. A correlated subquery describes a per-row dependency, not a promise that the database will run the inner query separately for every row. Use EXPLAIN to see the plan the optimizer chose.