Sub topic 3
Filtering with IN and multi-row subqueries
A scalar subquery returns one value. Many questions need a set of values instead: the customers who placed a large order, or the employees who work in a certain city. This chapter covers subqueries that return many rows, and the IN operator that tests a value against them.
This chapter assumes you can write SELECT with WHERE and ORDER BY, use aggregates with GROUP BY, and join tables. It also assumes you know that NULL means "unknown" and that comparisons with it are neither true nor false.
Sample data
The examples use four small tables. You can run this script in PostgreSQL, MySQL, or SQLite.
CREATE TABLE departments (
id INTEGER PRIMARY KEY,
name VARCHAR(50),
city VARCHAR(50)
);
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name VARCHAR(50),
salary NUMERIC(10,2),
department_id INTEGER
);
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name VARCHAR(50),
status VARCHAR(20)
);
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER,
total NUMERIC(10,2)
);
INSERT INTO departments VALUES
(10, 'Sales', 'London'),
(20, 'Engineering', 'Berlin'),
(30, 'Support', 'London');
INSERT INTO employees VALUES
(1, 'Mia', 5000, 10),
(2, 'Noah', 6500, 20),
(3, 'Olu', 4200, 30),
(4, 'Pia', 7000, 10);
INSERT INTO customers VALUES
(1, 'Ada', 'active'),
(2, 'Ben', 'active'),
(3, 'Cy', 'closed'),
(4, 'Dee', 'active');
INSERT INTO orders VALUES
(1, 1, 150),
(2, 1, 80),
(3, 2, 60),
(4, 4, 220),
(5, 4, 300);What "multi-row" means
A subquery is classified by the shape of its result. A scalar subquery returns one column and at most one row. A multi-row subquery returns one column and any number of rows, including zero. You can think of that result as a list of values.
Because the result is a list, you cannot compare it with =, >, or < directly. This query fails:
SELECT name
FROM customers
WHERE id = (SELECT customer_id FROM orders WHERE total > 100);The inner query returns three rows (1, 4, and 4). PostgreSQL reports more than one row returned by a subquery used as an expression. MySQL reports Subquery returns more than 1 row. SQLite does not raise an error here. It silently uses the first row, which is worse, because the result looks plausible and is wrong.
Testing membership with IN
IN asks whether a value appears in a list. You already know the form with literals, such as status IN ('active', 'pending'). Replacing the literals with a subquery gives you a list that comes from the data:
SELECT name
FROM customers
WHERE id IN (SELECT customer_id FROM orders WHERE total > 100);This returns Ada and Dee. Conceptually the database does two things:
- It runs the inner query and gets the list 1, 4, 4.
- For each customer, it checks whether
idis in that list and keeps the row if so.
This is a mental model. The optimizer is free to execute the query differently, for example by turning it into a semi-join. The result must be the same as if it had followed the two steps above.
Rules for the inner query
The subquery on the right side of IN must follow a few rules.
- One column only.
IN (SELECT id, total FROM orders)fails, because a single value cannot be compared with a two-column row. - Compatible types. The outer expression and the subquery column must be comparable. Matching an integer id against a text column raises an error in strict databases and may cause implicit conversions in others.
- Duplicates are harmless. Dee appears twice in the list, but
INonly asks whether a match exists. The outer query returns Dee once. - An empty list matches nothing. If no order exceeds 100, the inner query returns zero rows and the outer query returns zero rows. No error occurs.
- ORDER BY is pointless. A list has no order for membership purposes, so sorting inside an
INsubquery only costs time. Some databases reject it, and others ignore it.
The subquery can use a different table
The outer and inner queries do not need to share a table. The inner query often reads the table you would otherwise have to join:
SELECT name, salary
FROM employees
WHERE department_id IN (
SELECT id FROM departments WHERE city = 'London'
);This returns Mia, Olu, and Pia. The query answers "who works in a London department?" without exposing any department columns in the result. If you needed the department name in the output too, a join would be the better tool. That choice is covered in a later chapter.
Subqueries can also be nested. The inner query can itself contain an IN subquery:
SELECT name
FROM customers
WHERE id IN (
SELECT customer_id
FROM orders
WHERE total > (SELECT AVG(total) FROM orders)
);Here the innermost query is scalar (the average order total, 162), the middle query is multi-row (customers with a larger order), and the outer query returns their names. Each level runs inside the one above it. Past two or three levels, readability drops fast. Use a CTE instead, which a later chapter covers.
IN versus a join: duplicates
You can express the first example as a join:
SELECT c.name
FROM customers c
JOIN orders o ON o.customer_id = c.id
WHERE o.total > 100;This returns Ada once and Dee twice, because Dee has two matching orders and a join produces one output row per matching pair. Adding DISTINCT fixes that. The IN form never multiplies rows, because it only tests membership. When the question is "which customers have at least one such order?", IN states the intent directly.
Row constructors
PostgreSQL, MySQL, and Oracle let you compare several columns at once by wrapping them in parentheses:
SELECT id, total
FROM orders
WHERE (customer_id, total) IN (
SELECT customer_id, MAX(total)
FROM orders
GROUP BY customer_id
);This returns each customer's largest order. The subquery returns two columns, and the left side supplies a matching pair. SQL Server and SQLite versions before 3.15 do not support this form.
NULL inside the list
IN behaves as a series of OR comparisons. Suppose orders.customer_id contains a NULL. For id IN (1, 4, NULL), a customer with id 1 still matches, because one true comparison makes the whole OR true. A customer with id 2 gets "unknown" instead of false. In a WHERE clause, unknown rows are dropped, just as false rows are. So with plain IN, the NULL has no visible effect.
That is not true once you negate the test with NOT IN. The next chapter explains why and what to use instead.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `Subquery returns more than 1 row` | Used `=` or `>` against a multi-row subquery | Use `IN`, or `ANY`/`ALL` |
| `Operand should contain 1 column(s)` (MySQL) | Subquery selects more than one column | Select one column, or use a row constructor on both sides |
| Every row is returned | Column name in the subquery resolved to the outer table | Qualify names with aliases |
| Result differs from a join | Join duplicated rows | Compare with `SELECT DISTINCT` or use `IN` |
The third row deserves a closer look. If a column name does not exist in the inner table, the database looks for it in the outer query. Suppose a table blocked has a column customer_id but no id column:
SELECT name
FROM customers
WHERE id IN (SELECT id FROM blocked);The inner id is not found in blocked, so it resolves to customers.id. The condition becomes "id is in the list of customers' own ids", which is true for every row whenever blocked has any rows. Nothing raises an error. Writing SELECT b.customer_id FROM blocked b and qualifying every column avoids this class of bug.
Using IN with data-modifying statements
The same list-from-a-query pattern works in DELETE and UPDATE. A later chapter covers this in detail. The key point here is that the inner query identifies the rows and the outer statement acts on them:
DELETE FROM orders
WHERE customer_id IN (
SELECT id FROM customers WHERE status = 'closed'
);Run the matching SELECT first to confirm which rows will be affected.
Exercise
Write a query that returns the names of employees who work in a department located in Berlin, using IN with a subquery. Which names does it return on the sample data, and why can a join return the same employee more than once while this query cannot?
Show answer
SELECT name FROM employees WHERE department_id IN (SELECT id FROM departments WHERE city = 'Berlin'); returns only Noah, because Engineering (id 20) is the only Berlin department. IN only tests whether the employee's department_id appears in the list, so each employee row is kept or dropped once. A join produces one output row for each matching pair, so an employee would repeat if several department rows matched. With these tables each department id is unique, so no repeats occur here, but IN guarantees it regardless of the data.
Exercise
This query is meant to list customers who have an order, but it fails in PostgreSQL: SELECT name FROM customers WHERE id IN (SELECT customer_id, total FROM orders);. What is wrong, and how do you fix it?
Show answer
The subquery returns two columns, but IN with a single value on the left needs a one-column list. Remove the extra column: SELECT name FROM customers WHERE id IN (SELECT customer_id FROM orders);.