SQL Subqueries
Use the result of one query inside another query.
How it works
A subquery is a query nested inside another statement. It can return a single value, a list or a derived dataset depending on where it is used.
For clarity, start with a simple inner query and verify its output before embedding it. For repeated or complex logic, a CTE can often be easier to read.
Find materials above average consumption, suppliers slower than the global average or orders containing exception items.
The pattern
SELECT columns
FROM table
WHERE value > (SELECT AVG(value) FROM table);Example
SELECT ProductName, Price
FROM Products
WHERE Price > (SELECT AVG(Price) FROM Products);Run the example
Edit the query and run it against the built-in demo tables. Nothing is sent to a server.
The learning runner supports SELECT, WHERE, LIKE, IN, BETWEEN, GROUP BY, HAVING, JOIN, aggregates, ORDER BY and LIMIT. Advanced lessons explain additional production SQL concepts even when the mini runner does not execute that syntax.
Where can a scalar subquery be useful?
Progress is stored only in this browser. No account required.