Sub topic 6
Using IN with a Subquery
This chapter assumes you can write a basic SELECT with a WHERE clause, you know what IN does with a literal list of values, and you have seen AND, OR, and NULL before. It covers how IN works when the list comes from another query, where this form is useful, and where it goes wrong.
From a literal list to a subquery
A literal IN list is fixed at the time you write the query. Often the values you want to test against live in another table. A subquery lets the database build the list for you each time the query runs.
SELECT id, name
FROM employees
WHERE department_id IN (
SELECT id
FROM departments
WHERE location = 'Berlin'
);The subquery in parentheses runs a SELECT against departments. It returns the ids of all departments located in Berlin. The outer query keeps an employee row only if that employee's department_id equals one of those ids.
If a department moves from Berlin to Munich, you do not edit the query. The result changes because the data changed.
Rules for the subquery
The subquery used with IN must follow a few rules:
- It must return exactly one column. The number of columns must match the left side of
IN. - The column types must be comparable with the left-hand expression. Comparing an integer to a text column may fail or force a type conversion, depending on the database.
- It may return zero, one, or many rows. Zero rows is allowed and means the
INtest is false for every outer row. - It does not need
DISTINCT. Duplicate values in the subquery result do not produce duplicate rows in the outer result, because each outer row is tested once.
A subquery that returns two columns fails with an error such as "subquery has too many columns" (the wording varies by database).
-- Fails: the subquery returns two columns, but the left side is one column
SELECT id, name
FROM employees
WHERE department_id IN (
SELECT id, location
FROM departments
);Some databases, including PostgreSQL, MySQL, and Oracle, accept a row constructor on the left side, such as WHERE (a, b) IN (SELECT x, y FROM t). SQL Server does not. If you need portability, use EXISTS.
How the database evaluates it
Conceptually, the database runs the subquery first, collects the values, and then tests each outer row against them. This is the working model, and it is enough for writing correct queries.
In practice the optimizer is free to rewrite the query. It often turns an IN subquery into a semi-join, which is a join that returns each outer row at most once and never multiplies rows. The results are the same as the working model, but the plan can be much faster. Modern optimizers in PostgreSQL, MySQL 8, SQL Server, and Oracle handle this well. Older versions, particularly MySQL before 5.6, could run the subquery once per outer row and perform badly on large tables.
The diagram below shows the working model.
Uncorrelated and correlated subqueries
The Berlin example is an uncorrelated subquery. It does not refer to any column of the outer query, so it has the same result for every outer row and can be evaluated once.
A correlated subquery refers to the outer query's columns, so its result can differ for each outer row. You can use correlation inside IN, though EXISTS is usually clearer for this.
SELECT e.id, e.name
FROM employees e
WHERE e.salary IN (
SELECT MAX(e2.salary)
FROM employees e2
WHERE e2.department_id = e.department_id
);This returns employees whose salary equals the highest salary in their own department. The reference e.department_id in the subquery ties it to the current outer row.
Choosing between IN, EXISTS, and JOIN
Three constructs can express "rows in A that have a match in B." They are not always interchangeable.
| Construct | Duplicates in the inner table | Handling of NULL | Typical use |
|---|---|---|---|
| `IN (subquery)` | No duplicate outer rows | `NOT IN` breaks if the subquery returns NULL | Simple membership test on one column |
| `EXISTS (subquery)` | No duplicate outer rows | Not affected by NULL in the inner column | Correlated tests, multiple conditions, anti-joins |
| `JOIN` | Outer rows repeat once per match | NULL keys never match | When you also need columns from the inner table |
The key difference between IN and a plain JOIN is duplicates. If an employee belongs to a department that appears twice in the subquery result, IN still returns the employee once. A join against a table with repeated keys returns the employee twice.
-- May return an employee more than once if matching keys repeat in the right table
SELECT e.id, e.name
FROM employees e
JOIN departments d ON d.id = e.department_id
WHERE d.location = 'Berlin';Here departments.id is normally a primary key, so there are no repeats and the join is safe. When the inner key is not unique, prefer IN or EXISTS.
NULL inside the subquery
IN follows three-valued logic. x IN (a, b, c) behaves like x = a OR x = b OR x = c. A comparison with NULL yields unknown, not false. For IN this has little effect: a row that matches is kept, and a row that does not match is dropped, whether the result is false or unknown.
Negation changes this. x NOT IN (a, b, NULL) behaves like x <> a AND x <> b AND x <> NULL. The last term is unknown for every x. A row can only pass if all terms are true, so no row passes. A single NULL in the subquery result makes NOT IN return no rows at all.
Suppose orders.customer_id allows NULL because some orders were placed by guests.
-- Returns no rows if any orders.customer_id is NULL
SELECT c.id, c.name
FROM customers c
WHERE c.id NOT IN (
SELECT customer_id
FROM orders
);Even when many customers have no orders, this returns nothing, and it gives no error. This is the usual way the problem appears: a query that worked for months stops returning rows after the first NULL is inserted.
There are two reliable fixes. The first is NOT EXISTS:
SELECT c.id, c.name
FROM customers c
WHERE NOT EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.id
);The comparison o.customer_id = c.id is unknown for a NULL customer_id, so that inner row never matches, and it cannot block the outer row.
The second fix is to filter the NULL values out of the subquery:
SELECT c.id, c.name
FROM customers c
WHERE c.id NOT IN (
SELECT customer_id
FROM orders
WHERE customer_id IS NOT NULL
);A NULL on the left side matters too. If c.id is NULL, then c.id IN (...) is unknown, and c.id NOT IN (...) is also unknown, so the row is dropped in both cases. An empty subquery is the one exception: x NOT IN (empty set) is true for every x, including NULL, because there are no terms to be unknown.
Common errors
- Column count mismatch. The subquery returns more than one column and the left side has one. Select only the column you compare against.
- Wrong column in the subquery. Writing
SELECT id FROM orderswhen you meantSELECT customer_id FROM ordersruns without error if both are integers, and returns the wrong rows. Name the column deliberately. - Unqualified column names resolving to the outer query. If the subquery refers to a column that does not exist in its own tables, SQL looks outward and may bind to a column of the outer query. The subquery then becomes correlated by accident. Qualify column names with table aliases to avoid this.
- Forgetting
NOT INwithNULL. Covered above. - Large subquery results. Some databases limit literal
INlists, for example Oracle allows at most 1000 expressions in a list. A subquery has no such limit, which is one reason to use it instead of building a long list in application code.
A worked example
Consider these tables:
CREATE TABLE departments (
id INTEGER PRIMARY KEY,
name VARCHAR(50) NOT NULL,
location VARCHAR(50)
);
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name VARCHAR(50) NOT NULL,
department_id INTEGER
);
INSERT INTO departments (id, name, location) VALUES
(1, 'Sales', 'Berlin'),
(2, 'Support', 'Berlin'),
(3, 'Finance', 'Madrid'),
(4, 'Legal', NULL);
INSERT INTO employees (id, name, department_id) VALUES
(1, 'Anna', 1),
(2, 'Ben', 2),
(3, 'Carla', 3),
(4, 'Dev', NULL);The query for Berlin employees returns Anna and Ben. Carla works in Madrid, and Dev has no department, so NULL IN (1, 2) is unknown and Dev is dropped.
Now ask for employees who are not in a Berlin department:
SELECT id, name
FROM employees
WHERE department_id NOT IN (
SELECT id
FROM departments
WHERE location = 'Berlin'
);This returns Carla only. The subquery returns ids 1 and 2, with no NULL, so the NOT IN trap does not apply here. Dev is still excluded because his department_id is NULL, and the comparison is unknown. If you want Dev included, state it explicitly:
SELECT id, name
FROM employees
WHERE department_id IS NULL
OR department_id NOT IN (
SELECT id
FROM departments
WHERE location = 'Berlin'
);Now change the subquery to filter on location <> 'Berlin' and select location instead of id, and you would be comparing the wrong values. Always check that the subquery's selected column matches the meaning of the outer column.
Index considerations
An IN subquery can use indexes on both sides. An index on employees.department_id lets the optimizer look up employees for each matching department, and an index on departments.location speeds up the subquery itself. Because the optimizer often rewrites IN as a semi-join, check the execution plan (EXPLAIN in PostgreSQL and MySQL) rather than assuming a particular strategy. Wrapping the outer column in a function, such as LOWER(department_name) IN (...), prevents ordinary index use on that column.
Exercise
The table orders has a nullable column customerid. A colleague writes SELECT id FROM customers WHERE id NOT IN (SELECT customerid FROM orders); and gets zero rows, although several customers have never ordered. Explain why, and rewrite the query so it returns those customers.
Show answer
At least one row in orders has customerid NULL. NOT IN expands to id <> a AND id <> b AND ... AND id <> NULL, and the last comparison is unknown for every customer, so no row can evaluate to true. Rewrite with NOT EXISTS: SELECT c.id FROM customers c WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customerid = c.id); or keep NOT IN and add WHERE customer_id IS NOT NULL to the subquery.
Exercise
Using the departments and employees tables from the worked example, write a query that returns the names of employees who work in a department whose location is NULL or Madrid. Which employees does it return?
Show answer
SELECT name FROM employees WHERE departmentid IN (SELECT id FROM departments WHERE location = 'Madrid' OR location IS NULL); It returns Carla (department 3, Madrid). Department 4 (Legal) has a NULL location, but no employee belongs to it. Dev has a NULL departmentid, so the IN test is unknown and he is not returned.