Subqueries — SQL

A subquery is a query in parentheses, inside another query. The subquery runs first, then the outer query (the query around it) uses its result. WHERE price >…

Who in your class is taller than average? You can't answer right away. First the class's average height has to be calculated (the small question). Then every student's height is compared with that number (the big question). So one question turns out to hold two, and the small one has to be answered first.

In SQL, this pattern is written with a subquery: a query inside another query, written in parentheses. The small question becomes the subquery, or inner query, and runs first. The big question becomes the outer query, which uses the inner query's result.

Why you need a subquery

The first idea you might try doesn't work. SQLite refuses it with the error written in the comment line:

SELECT name, price FROM products
WHERE price > AVG(price);
-- misuse of aggregate function AVG()

WHERE checks one row at a time: "is this row's price more than ...?". But AVG(price) needs all the rows to be calculated. The two can't be mixed in one WHERE, so SQLite refuses. The fix: calculate the average in a separate query, and put that query in parentheses.

Step by step

The products table holds five products: Laptop 1,200, Mouse 15, Monitor 350, Keyboard 50 and Headset 75. The query below takes the products priced above the average. Before you follow the steps, guess: how many products pass?

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

Step 1, the inner query. SELECT AVG(price) FROM products adds all the prices together (1,690 in total), then divides by the 5 products: 338. The result is one number.

Step 2, the outer query. The parentheses that hold the inner query are replaced by that number. So the condition is now WHERE price > 338, and every row is checked:

name price price > 338?
Laptop 1,200 yes
Mouse 15 no
Monitor 350 yes
Keyboard 50 no
Headset 75 no

Only 2 products pass: Laptop and Monitor. The Laptop's very high price raises the average.

A subquery that returns a list: IN

A subquery can also return one column with many rows, which is a list. Use that list with IN. Take the customers and orders from the JOIN lessons (Budi, Siti, Andi, and the orders Laptop, Mouse, Monitor, Webcam):

SELECT name FROM customers
WHERE id IN (SELECT customer_id FROM orders);

The inner query takes the customer_id of every order, so it returns the list 1, 1, 2, NULL. The outer query takes the customers whose id is in that list: Budi and Siti. Each appears once, even though Budi has two orders, while an INNER JOIN would show Budi twice. That's the advantage of IN over a JOIN when you only need "who", not "which orders".

📌 A subquery in SELECT

A subquery can be a column too. The subquery below runs once for every customer, because it uses c.id from the outer query:

SELECT c.name,
  (SELECT COUNT(*) FROM orders o WHERE o.customer_id = c.id) AS order_count
FROM customers c;

The result is Budi 2, Siti 1, Andi 0. A subquery that uses a column of the outer query (here c.id) is called a correlated subquery.

⚠️ Hard-coded numbers, an empty NOT IN, forgotten parentheses

TL;DR: A subquery is a query in parentheses, inside another query. The subquery runs first, then the outer query (the query around it) uses its result. WHERE price > (SELECT AVG(price) FROM products) first calculates the average price, 338, then takes the products priced above it: the Laptop and the Monitor. WHERE price > AVG(price) fails because WHERE checks one row at a time, while AVG needs every row. Use a subquery that returns one value with >, <, =. Use a subquery that returns a list with IN. Be careful with NOT IN when the list can hold a NULL: the result has 0 rows.

⚡ Why you need a subquery

Guess first: you want the products priced above the average. Does WHERE price > AVG(price) run?

It's refused: misuse of aggregate function AVG(). WHERE checks one row at a time, while AVG needs every row.

Meaning: The average has to be calculated first, by another query written in parentheses. The query in parentheses is called a subquery.

⚡ A query inside a query

Write:

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

Meaning: The inner query (in the parentheses) runs first and gives one number: the average price, 338. The outer query (the query around the parentheses) then takes the products priced above that number: the Laptop and the Monitor.

In the exercise, the checker looks at whether the average is calculated with (SELECT AVG(...) ...), not a number typed in.

⚡ A list with IN

Write:

SELECT name FROM customers
WHERE id IN (SELECT customer_id FROM orders);

Meaning: The inner query takes the customer_id of each order in the orders table, so it returns a list of customer numbers. A subquery that returns many rows is used with IN ("is in this list"). The outer query takes the customers in customers whose id is in that list: Budi and Siti, once each, even though Budi has two orders.

⚡ NOT IN and NULL

Meaning: NOT IN means "is not in this list". If the list holds a NULL, for example the customer_id of a guest order (a buyer with no account), NOT IN returns 0 rows, because a comparison with NULL is never true. Add WHERE customer_id IS NOT NULL inside the subquery, so no NULL gets into the list.

What you will learn