# 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.

Subject: SQL | Lesson 23 of 44 | 6 min read
Interactive lesson: https://codewithanimation.in/sql/subqueries
Previous: [Logical Order of a Query](https://codewithanimation.in/sql/logical-order-of-a-query.md) | Next: [EXISTS & Correlated Subqueries](https://codewithanimation.in/sql/exists-and-correlated-subqueries.md)

## 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

```sql
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.

```sql
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.

## Common mistake: NOT IN and NULL

`id NOT IN (SELECT customer_id FROM tickets)` returns no rows at all if even one ticket has a `NULL` customer_id. For an id that is not in the list, the database cannot rule out that the NULL is that id, so the answer is unknown, not true. `WHERE` keeps only true.

The same data with `IN` works fine, which makes this bug easy to miss. The safe fix is `NOT EXISTS`, which the next lesson covers, or adding `WHERE customer_id IS NOT NULL` inside the subquery.

A scalar subquery that returns several rows is an error: `more than one row returned by a subquery used as an expression`. Use `max()`, `min()` or a `LIMIT 1` with an `ORDER BY` when you need one value.

## Tip: Ask what shape the inner query gives back

Before you write the brackets, decide: one value (use a comparison), a list (use IN), or a table (use FROM). Run the inner query alone first, and check its result before you wrap it.

## Try it: 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.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/sql/subqueries

## Check yourself

### Question 1

`WHERE points > (SELECT avg(points) FROM players)` runs on `players`. In what order do the two queries run?

- A. The inner query first, then the outer query uses its value
- B. The outer query first, then the inner query
- C. Both at the same time, row by row

Correct answer: A

An uncorrelated subquery is independent of the outer query. It runs once and its value is reused for every row.

- Why not B: The outer query needs the inner answer to compare with, so the inner one has to run first.
- Why not C: That is how a correlated subquery behaves, and this one does not use the outer row. It runs once.

### Question 2

`tickets.customer_id` contains the values 1, 1, 2 and NULL. What does `SELECT ... FROM customers WHERE id NOT IN (SELECT customer_id FROM tickets)` return?

- A. No rows, because of the NULL in the list
- B. The customers with ids other than 1 and 2
- C. An error

Correct answer: A

For an id not in the list, NOT IN gives UNKNOWN when the list holds a NULL. WHERE keeps only TRUE, so every row is dropped.

- Why not B: That is what you would expect, but the NULL makes the test UNKNOWN for those ids, so WHERE drops them.
- Why not C: The query is valid. It just returns nothing.

### Question 3

A scalar subquery returns 8 rows instead of 1. What does PostgreSQL do?

- A. It raises an error: more than one row returned by a subquery used as an expression
- B. It uses the first row
- C. It uses NULL

Correct answer: A

A scalar subquery may return at most one row. With more, PostgreSQL stops with an error (SQLSTATE 21000).

- Why not B: PostgreSQL never picks a row for you. Some other databases do, which hides the mistake.
- Why not C: NULL is used only when the subquery returns no rows at all.

## 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.
