Skip to main content

Chapter 6 · Subqueries

SQL Subquery Practice

A subquery is a query inside another query. It lets you use one answer to get another, like products priced above the average or customers who placed an order last month.

You'll practise the three common shapes: a single value used in a comparison, a list used with IN or EXISTS, and a correlated subquery that runs once per row of the outer query.

Start practising54 exercises · 3 easy, 42 medium, 9 hard

Key ideas

Scalar subquery
Returns one value: WHERE price > (SELECT AVG(price) FROM products).
IN / NOT IN
Compare against a list. Careful: NOT IN with a NULL in the list returns nothing.
EXISTS / NOT EXISTS
True if the subquery returns any row: safe with NULLs and often faster.
Correlated subquery
References the outer row, e.g. each product compared with its own category's average.

Example: Products priced above the average

SELECT name, price
FROM products
WHERE price > (SELECT AVG(price) FROM products)
ORDER BY price DESC;

The inner query runs once and returns a single number that every product is compared against.

In interviews

If you write NOT IN, say how you handle NULLs, or use NOT EXISTS. It's a favourite trap question.

All 54 Subqueries exercises

Ordered from easiest to hardest. Each one runs on a real database with instant feedback.