Subquery
A subquery is a query nested inside another query. The inner query runs first, and its result is used by the outer query — for example, to filter on a calculated value.
SQL
Subqueries let you answer questions in steps, such as 'find users older than the average age.' The inner query computes the average, and the outer query compares each user to it.
A subquery can appear in WHERE, FROM, or SELECT, and can return a single value, a list of values (used with IN), or a whole table.
Syntax
SELECT columns FROM table_name
WHERE column OP (SELECT ... FROM ...);Examples
SQL
SELECT name, age
FROM users
WHERE age > (SELECT AVG(age) FROM users);Output:
name age
----- ---
Alice 30