Subqueries
Use one query inside another to compare against a calculated value or a list.
18 min
A subquery is a query inside brackets, used where a value or a list could go. It lets you answer questions in two steps in one statement.
"Which books cost more than the average?" needs the average first:
SELECT title, price
FROM books
WHERE price > (SELECT AVG(price) FROM books);The inner query returns one number (15.949), then the outer query compares each price with it.
"Which customers have placed an order?"
SELECT name FROM customers
WHERE id IN (SELECT customer_id FROM orders);The inner query returns a list of ids; IN keeps customers whose id is in it.
NOT IN (SELECT ...) finds customers who have no orders. But if the inner list contains even one NULL, NOT IN returns no rows at all, because "not equal to NULL" is never true. A safer form is NOT EXISTS:
SELECT name FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);That inner query refers to the outer row c, so it runs once per customer: a correlated subquery.
You can also put one in FROM, treating its result like a table. Give it an alias:
SELECT genre, avg_price FROM
(SELECT genre, AVG(price) AS avg_price FROM books GROUP BY genre)
WHERE avg_price > 15;Often either works. A join is natural when you need columns from both tables; a subquery reads well for "is in", "is not in", and "compared with a total".
Pick the tool by what you need back.
JOIN
- Need columns from the other table?
- yes
- Reads well for
- combining related facts in one row
- Watch out for
- duplicate rows if one row matches many
Best for reports across tables
IN / NOT IN subquery
- Need columns from the other table?
- no
- Reads well for
- filtering by membership in a list
- Watch out for
- NOT IN with a NULL in the list
Best for is / is not in a set
NOT EXISTS
- Need columns from the other table?
- no
- Reads well for
- finding rows with nothing related
- Watch out for
- must correlate to the outer row
Best for never ordered, never logged in
Scalar subquery
- Need columns from the other table?
- one value
- Reads well for
- comparing with an average, max or total
- Watch out for
- it must return exactly one value
Best for above average, highest
Show the title of every book that costs more than the average price of all books.
Tables you can query
- books (id, title, author, genre, price, year, stock)
SELECT title FROM books
WHERE price > (Show the name of every customer who has never placed an order.
Tables you can query
- customers (id, name, city, joined, email)
- orders (id, customer_id, order_date, status)
- order_items (order_id, book_id, qty)
SELECT name FROM customers
WHEREShow the name of every customer who has ever ordered a book in the 'science' genre (in any order). Each customer once.
Tables you can query
- books (id, title, author, genre, price, year, stock)
- customers (id, name, city, joined, email)
- orders (id, customer_id, order_date, status)
- order_items (order_id, book_id, qty)
SELECT name FROM customers
WHERE id IN (“`NOT IN` and `NOT EXISTS` always give the same answer.”
They both mean "is not in there", and on clean data the results match.
What is actually true
If the inner list contains a NULL, x NOT IN (...) is never true for any x, so you get an empty result. NOT EXISTS ignores that trap.
How to catch yourself
When the inner column can be NULL, prefer NOT EXISTS, or add `WHERE col IS NOT NULL` inside.
- A subquery in brackets can supply a single value, a list for
IN, or a table forFROM. > (SELECT AVG(...))compares each row with a calculated total.NOT EXISTSis safer thanNOT INwhen NULLs are possible.- A correlated subquery refers to the outer row and runs per row.
Subquery checks.
What must a subquery after price > return?
- AA list
- BOne value
- CA whole table
- DNothing
Which finds customers with no orders safely, even if some order rows have NULL customer ids?
- A`NOT IN (SELECT customer_id FROM orders)`
- B`NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id)`
- C`= (SELECT customer_id ...)`
- D`IN (SELECT ...)`
Which statement about a correlated subquery is true?
- AIt runs once for the whole query
- BIt refers to a column of the outer query
- CIt can never use WHERE
- DIt must be in FROM
A subquery used like a table in FROM needs an (a name).
Capitalisation, spacing and punctuation are ignored when grading.
SELECT title FROM books WHERE year = (SELECT MAX(year) FROM books); returns...
- AThe newest book(s)
- BThe oldest book
- CThe average year
- DAn error
Practise this lesson, not just read it
In BiliMind the questions above are marked when you answer, the flashcards come back on a schedule, and the rest of SQL for Beginners is planned around your week. Free.