SQL Subqueries

A subquery is a query inside another query, wrapped in parentheses. Use it when one answer depends on another, like “drinks that cost more than the average”.

Updated December 1, 2026

Syntax

SELECT columns
FROM table_name
WHERE column > (SELECT AGGREGATE(column) FROM table_name);

Compare to a single value

The inner query returns one number, the average price. The outer query uses it like a constant.

SELECT name, price
FROM drinks
WHERE price > (SELECT AVG(price) FROM drinks)
ORDER BY price DESC;
Result on the SQL Café sample data (6 rows)
nameprice
Matcha Latte5.25
Mocha5
Cold Brew4.75
Chai Latte4.75
Latte4.5
Cappuccino4.25

Filter with a list

With IN, the subquery can return many values: departments that have someone earning over $150,000.

SELECT name
FROM departments
WHERE id IN (SELECT department_id FROM employees WHERE salary > 150000);
Result on the Acme Co. (company data) sample data (2 rows)
name
Engineering
Sales

Query a subquery’s result

A subquery in FROM acts like a temporary table. Here we total each order, then average those totals.

SELECT COUNT(*) AS orders, ROUND(AVG(total), 2) AS avg_order_value
FROM (
  SELECT i.order_id, SUM(i.quantity * p.price) AS total
  FROM order_items AS i
  JOIN products AS p ON p.id = i.product_id
  GROUP BY i.order_id
) AS order_totals;
Result on the Desk & Co. (online store) sample data (1 row)
ordersavg_order_value
10115.25

Common mistakes

Practice Subqueries interactively

Write real queries in your browser and get instant feedback in the lesson “Subqueries in WHERE” (Unit 6). New learners can start free from the first lesson.

Frequently asked questions

Subquery or JOIN: which is better?

Use whichever reads more clearly. Databases often run them the same way. JOINs are better when you need columns from both tables.

What is a correlated subquery?

One that refers to the outer query’s row, so it runs once per row. It’s powerful but can be slow; window functions often do the same job faster.

Related SQL tutorials