10. Subqueries
Queries inside queries, and when each kind fits.
The lesson
Subqueries
"Which tracks run longer than average?" — you can't answer that without first knowing the average. So far every query has been a single question, but real questions arrive in layers: find the average, then compare, then list. SQL answers layered questions with subqueries: full SELECTs nested inside other SELECTs, wrapped in parentheses.
Subqueries sound exotic, but they're really the same tool you've been using all along, placed somewhere new. This chapter shows the three places a subquery can sit — in WHERE, in FROM, in SELECT — and the three things it can hand back: a single value, a list, or a whole table.
The average track: a subquery in WHERE
Start with the average duration of everything in tracks:
SELECT AVG(duration_sec) FROM tracks;
One number comes back: just over 259 seconds. Now combine: a subquery in WHERE computes the average inside the comparison, before the outer query runs:
SELECT title, duration_sec
FROM tracks
WHERE duration_sec > (SELECT AVG(duration_sec) FROM tracks);
Read it as two questions: "what is the average duration?" then "which tracks beat it?" Twenty-two tracks are longer than average — and the query never needs to know the number 259. Add a new track tomorrow and the subquery adjusts by itself.
Because it returns a single value (one row, one column), this is a scalar subquery, and you can use it anywhere a value goes: with >, <, =, <>.
A list to check against: IN and NOT IN
Some subqueries return many rows. The radio show wants albums whose artists come from Spain:
SELECT title
FROM albums
WHERE artist_id IN (SELECT id FROM artists WHERE country = 'Spain');
The inner query returns the ids of the Spanish artists (2 and 10); the outer query then asks, for each album, "is my artist_id in that list?" Three albums come back: Mar Adentro, Las Luces and Desde Dentro. You could have typed the list by hand — IN (2, 10) — but the list must stay true to the data, and only a query can guarantee that.
NOT IN is the mirror: same shape, opposite answer.
SELECT title
FROM albums
WHERE artist_id NOT IN (SELECT id FROM artists WHERE country = 'USA');
Thirteen albums — everything made outside the United States.
Careful with NOT IN and NULL. If the subquery's list contains a
NULL,NOT INreturns no rows at all:NULL NOT IN (...)is neither true nor false, so every row fails the test. None of the countries inartistsareNULLtoday, but the column allowsNULL, which is enough to make the habit matter. When NULLs are possible,EXISTS(next section) is the safer choice.
EXISTS: "is there at least one?"
EXISTS asks a yes/no question about each outer row. Which artists have at least one album?
SELECT name
FROM artists
WHERE EXISTS (SELECT 1 FROM albums WHERE albums.artist_id = artists.id);
Watch the magic line: albums.artist_id = artists.id. The inner query is not standalone — it sees the outer row it's currently working on. That's a correlated subquery: for each of the twelve artists, SQL runs the inner check once. The SELECT 1 is a placeholder — EXISTS only cares whether any rows come back, so the column doesn't matter.
All twelve artists qualify. "Is there at least one X?" is so common that EXISTS was built for it.
Correlated counting
The same pattern, but counting. Which albums have more than two tracks?
SELECT title
FROM albums a
WHERE (SELECT COUNT(*) FROM tracks t WHERE t.album_id = a.id) > 2;
Two aliases, two tables: the outer album is a, the inner track is t. For each album, the inner query counts only its own tracks, and the outer comparison keeps albums over the limit — fifteen of the seventeen. (The two live and anthology albums, with two tracks each, are the odd ones out.)
Any aggregate from chapter 5 can live inside a correlated subquery: AVG, SUM, MIN...
A table inside FROM
Both subqueries so far sat in WHERE. A subquery can also replace the table itself in FROM: the inner query runs first, produces a whole table, and the outer query selects from it. Such a subquery is called a derived table.
Marketing wants the average customer spend. That's an "average of totals" — impossible in one GROUP BY, because you'd need to group first, then average the groups. Two levels fix it:
SELECT AVG(total)
FROM (SELECT customer_id, SUM(total) AS total
FROM invoices
GROUP BY customer_id);
The inner query computes each customer's lifetime total (15 customers, one row each); the outer query averages those 15 numbers: 3.574. Notice the inner query aliases its computed column (AS total) — that name is what the outer query reads.
A query as a column
The last placement: a subquery in the SELECT list, one value per row. Each customer, with their invoice count alongside:
SELECT first_name, last_name,
(SELECT COUNT(*) FROM invoices i WHERE i.customer_id = c.id) AS invoice_count
FROM customers c;
This is correlated too — for each customer, the inner query counts that customer's invoices. Because a SELECT column shows exactly one value per row, this subquery must be scalar: at most one row, one column. If it ever returned two rows, the query would crash.
Joins vs subqueries
By now you may be thinking: "didn't chapter 9 do all this with joins?" Yes — many questions have two spellings. The Spanish-albums question as a join:
SELECT DISTINCT albums.title
FROM albums
JOIN artists ON artists.id = albums.artist_id
WHERE artists.country = 'Spain';
Same answer, three rows. The rule of thumb:
| You want... | Reach for... |
|---|---|
| ...a value to compare against | scalar subquery |
| ...membership in a list | IN / NOT IN |
| ...to test existence, without duplicates | EXISTS |
| ...the other table's columns in the result | join |
| ...to filter each row by its own aggregate | correlated subquery |
| ...an "average of averages" question | subquery in FROM |
| ...a computed value next to each row | subquery in SELECT |
Both styles are legitimate, and the database often treats them the same. Write what reads most clearly; that's the query you'll still understand next week.
What you just learned
- A subquery is a full
SELECTin parentheses; it can live inWHERE,FROM, orSELECT. - Scalar subqueries return one value and work with
=,>,<. IN/NOT INtest membership in a subquery's list — andNOT INturns hostile whenNULLis in the list.EXISTSasks "is there at least one?", and correlated subqueries can count or sum per outer row.- Derived tables in
FROMlet you query the result of a query. - Subqueries and joins are often two spellings of the same question.
Dialect note. Everything in this chapter is standard SQL and behaves the same in PostgreSQL and MySQL. One portability trap: PostgreSQL demands an alias for derived tables (
FROM (SELECT ...) AS x), while SQLite lets you skip it — write the alias anyway. AndLIMITinside a subquery is a convenience that some databases don't accept.
The boss exercise of this chapter stacks joins, grouping, ordering and a scalar subquery in one query. If you can write it, you can answer any "top of the ranking" question the store ever asks.