Subqueries
A subquery (or nested query) is a SQL query placed inside another query - used to compute an intermediate result that the outer query then filters, compares against, or otherwise builds on.
Subquery in a WHERE Clause
-- Customers who have placed at least one order above 5000
SELECT * FROM customers
WHERE customer_id IN (
SELECT customer_id FROM orders WHERE amount > 5000
);
Subquery in a SELECT Clause
-- Show each customer alongside their total number of orders
SELECT first_name,
(SELECT COUNT(*) FROM orders o WHERE o.customer_id = c.customer_id) AS order_count
FROM customers c;
Subquery in a FROM Clause
-- Treat a subquery's result as a temporary table
SELECT city, AVG(total_spent)
FROM (
SELECT c.city, SUM(o.amount) AS total_spent
FROM customers c
JOIN orders o ON c.customer_id = o.customer_id
GROUP BY c.customer_id, c.city
) AS customer_totals
GROUP BY city;
Correlated vs Non-Correlated Subqueries
A non-correlated subquery runs independently of the outer query and executes once. A correlated subquery references a column from the outer query and re-runs for every row the outer query processes - more flexible, but often slower.
How the Database Evaluates a Subquery
It helps to picture the work in order. For a non-correlated subquery in a WHERE clause, the database conceptually runs the inner query first, builds the list or value it returns, and then checks each outer row against it. For a correlated subquery, the inner query is tied to the current outer row, so logically it is evaluated again for each row. Modern optimisers often rewrite both forms into joins behind the scenes, which is why the execution plan matters more than how the query looks.
Subqueries also come in three result shapes, and the shape decides where you can use them:
- Scalar: exactly one value, usable with
=,>or in aSELECTlist. - Single column, many rows: usable with
IN,ANYorALL. - Table: many rows and columns, usable in
FROMas a derived table.
Worked Example: Above-Average Spenders
Business question: which customers spent more than the average customer? This needs a two-level calculation, which is exactly what subqueries are good at.
SELECT c.customer_id, c.first_name, t.total_spent
FROM customers c
JOIN (
SELECT customer_id, SUM(amount) AS total_spent
FROM orders
GROUP BY customer_id
) AS t ON t.customer_id = c.customer_id
WHERE t.total_spent > (
SELECT AVG(total_spent)
FROM (
SELECT SUM(amount) AS total_spent
FROM orders
GROUP BY customer_id
) AS per_customer
);
The derived table t totals each customer, the scalar subquery finds the average of those totals, and the outer query keeps only customers above it. The same logic reads more cleanly with a common table expression (CTE):
WITH totals AS (
SELECT customer_id, SUM(amount) AS total_spent
FROM orders
GROUP BY customer_id
)
SELECT c.first_name, t.total_spent
FROM totals t
JOIN customers c ON c.customer_id = t.customer_id
WHERE t.total_spent > (SELECT AVG(total_spent) FROM totals);
EXISTS, IN and NOT IN
EXISTS asks only whether at least one matching row exists, so the database can stop at the first match:
SELECT c.first_name
FROM customers c
WHERE EXISTS (
SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id
);
Be careful with NOT IN. If the subquery returns even one NULL, the condition can never be true and the query returns no rows. NOT EXISTS does not have this problem, so prefer it for "customers with no orders" style questions.
Common Mistakes and Checklist
- Using
=with a subquery that returns several rows, which raises an error. - Forgetting the alias on a derived table; most databases require one.
- Nesting many levels deep when a CTE would be clearer.
- Assuming a correlated subquery is always slow; check the execution plan with
EXPLAIN.
Checklist: decide the result shape, pick IN, EXISTS or a derived table accordingly, watch for NULLs, and compare with a JOIN or CTE on real data volumes.