Subqueries
Use the answer of one query inside another as a value, a list or a table, and avoid the NOT IN trap that returns nothing.
A query inside a query
A subquery is a SELECT written inside brackets inside another query. The inner query runs first, and its answer is handed to the outer query.
The answer can be one value (a scalar subquery), a list of values (used with IN), or a whole table (used in FROM).
Questions that depend on another answer
"Which players scored above the average?" needs the average first. "Which customers have placed an order?" needs the list of customers in the orders table first. A subquery lets one statement ask both questions.
Three shapes
SELECT name, points
FROM players
WHERE points > (SELECT avg(points) FROM players);The inner query returns one value, 25.5. The outer query keeps the players whose points are above it: Asha and Gus. A scalar subquery must return exactly one column and at most one row. With no rows it is NULL, and with more than one row PostgreSQL stops with an error.
SELECT name FROM customers
WHERE id IN (SELECT customer_id FROM orders);Here the inner query returns a list (1, 1, 2), and IN is true when the id appears in it. A subquery in FROM works like a table: FROM (SELECT team, count(*) AS n FROM players GROUP BY team) AS t. Give it a name, as the SQL standard requires one.
Try the five shapes
Switch between the kinds and read the badge column to see TRUE, FALSE or UNKNOWN for each row. Then pick NOT IN with a NULL, and Too many rows.
| avgnumeric |
|---|
| 25.5 |
| nametext | pointsinteger | WHERE |
|---|---|---|
| Asha | 31 | TRUE |
| Ben | 17 | FALSE |
| Chen | NULL | UNKNOWN |
| Dara | 24 | FALSE |
| Eli | NULL | UNKNOWN |
| Fay | 24 | FALSE |
| Gus | 40 | TRUE |
| Hana | 17 | FALSE |
| nametext | pointsinteger |
|---|---|
| Asha | 31 |
| Gus | 40 |
The inner query runs once and returns 25.5 (6 players have points, 153 / 6). The outer query then compares each player's points with it. Chen and Eli have NULL points, so their test is UNKNOWN and they are left out.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- A subquery is a SELECT in brackets: it gives one value, a list, or a table.
- A scalar subquery with no rows is NULL, and with more than one row it is an error.
- x IN (list) is true on a match. NOT IN returns nothing if the list holds a NULL.
- An uncorrelated subquery runs once, before the outer query uses its answer.
Done with this concept?
Mark it complete to track your progress. No login needed.