Subquery
In one line
A subquery is a SELECT statement nested inside another SQL statement — its result is used by the outer query.
In simple words
A subquery is a query inside a query. The inner query runs first and its result is used by the outer query. Subqueries can appear in the SELECT list, FROM clause, or WHERE clause.
For example, to find users who spent more than average:
SELECT * FROM orders WHERE total > (SELECT AVG(total) FROM orders);
The subquery SELECT AVG(total) FROM orders computes the average, and the outer query finds orders above that average.
Subqueries can be correlated (referencing the outer query) or uncorrelated (independent). They are powerful but can be slow — sometimes a JOIN is more efficient.
Example
-- Find orders above the average order value
SELECT * FROM orders
WHERE total > (SELECT AVG(total) FROM orders);The subquery computes the average order value; the outer query uses it as a threshold.
Related terms
Related Resources
Related Lessons
- Subqueries
Learn how to nest queries.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.