AnalystPracticeGuides
DashboardSign up

SQL subqueries

A subquery is a query inside another query. It can return one value for a comparison, a list for IN, or a whole table to select from. For longer logic, a CTE (WITH) does the same and reads more easily.

Watch it solved. Q7: the second highest salary with a subquery, from 4:30, in our video “SQL Interview Questions and Answers for Data Analysts (Easy to Hard)”. Pressing play loads the video from YouTube (privacy). Open on YouTube

One value: compare with an average

Orders above the average order:

SELECT * FROM orders
WHERE amount > (SELECT AVG(amount) FROM orders);

A list: IN or EXISTS

Customers who ordered in 2026:

SELECT name FROM customers c
WHERE EXISTS (SELECT 1 FROM orders o
WHERE o.customer_id = c.id AND o.order_date >= '2026-01-01');

This is a correlated subquery: it runs per customer and refers to c.id from the outer query.

A table: subquery in FROM

Average revenue per customer, in two steps:

SELECT AVG(total) FROM (
SELECT customer_id, SUM(amount) AS total
FROM orders GROUP BY customer_id
) t;

The same with a CTE

WITH totals AS (
SELECT customer_id, SUM(amount) AS total FROM orders GROUP BY customer_id
)
SELECT AVG(total) FROM totals;

Common mistake

A subquery used with = must return exactly one row. If it can return more, use IN, or you get an error (or, in SQLite, a silently wrong result based on the first row).

Try it yourself. Practise this in a real database in your browser, with instant feedback.
Practise subqueries

Updated November 2026.

← All free guides