Subqueries
A subquery is a full SELECT written inside another query's parentheses. SQL runs the inner one first, then uses its result as if it were a value the outer query already knew.
Query
SELECT name, price
FROM wines
WHERE price > (SELECT AVG(price) FROM wines)
ORDER BY price DESC;↓ result
name price
Xinomavro 16
Assyrtiko 14When the inner query returns a whole list instead of one number, compare against it with IN (or NOT IN for the opposite) instead of = or >.
Query
SELECT name, price
FROM wines
WHERE price <= (SELECT AVG(price) FROM wines)
ORDER BY price DESC;↓ result
name price
Agiorgitiko 12
Malagousia 11
Moschofilero 10
Mavrodafni 9A subquery can go anywhere a value or a list is expected: in a WHERE clause comparing against a single number, or feeding IN a whole list of matches pulled from another table entirely.