Sub topic 5
Testing membership with IN
This chapter assumes you can write a basic SELECT, filter with comparison operators (=, <, >), and combine conditions with AND and OR. It covers IN with a literal list of values. Subqueries, NOT IN and NULL behavior are covered in later chapters, so this chapter only previews them.
What IN does
IN is a predicate that tests whether a value matches any member of a list. A predicate is a condition that evaluates to true, false, or unknown for each row. WHERE keeps only the rows for which the predicate is true.
SELECT id, name, department
FROM employees
WHERE department IN ('Sales', 'Marketing', 'Support');This is shorthand for several equality tests joined by OR. The database treats the query above the same as this one:
SELECT id, name, department
FROM employees
WHERE department = 'Sales'
OR department = 'Marketing'
OR department = 'Support';The IN form is shorter and harder to get wrong. Its main advantage appears when you combine it with other conditions, because you no longer have to think about where parentheses belong.
Syntax and rules
The general form is:
expression IN (value1, value2, value3, ...)- The expression is usually a column, but it can be any expression, such as
UPPER(department)orsalary / 12. - The list sits inside parentheses and the values are separated by commas.
- The list items are normally literals, but they can also be columns, parameters, or expressions.
- The list must contain at least one value. An empty list,
IN (), is a syntax error in standard SQL and in most databases. - The values should have types compatible with the expression. Compare text to text and numbers to numbers.
The order of the list does not matter, and duplicate values are harmless. IN (1, 2, 2, 3) returns the same rows as IN (1, 2, 3).
Numbers, text, and dates
IN works with any type that supports equality.
SELECT id, name
FROM employees
WHERE id IN (3, 7, 12, 40);SELECT id, created_at
FROM orders
WHERE CAST(created_at AS DATE) IN ('2026-03-01', '2026-03-15', '2026-03-31');The second query uses an exact date match, so the CAST is needed when created_at holds a time of day. Otherwise a timestamp such as 2026-03-15 09:30:00 would not equal the date 2026-03-15. For ranges of dates, use the half-open range pattern from the chapter on date ranges, not IN.
Matching is exact
IN performs equality tests, so it does not use wildcards. This query looks for the literal text A%, not names that start with A:
SELECT id, name
FROM employees
WHERE name IN ('A%');To combine pattern matching with a list of alternatives, you must write separate LIKE conditions joined with OR.
SELECT id, name
FROM employees
WHERE name LIKE 'A%'
OR name LIKE 'B%';Text comparison also follows the database's collation rules. A collation is the set of rules that decides whether two strings are equal, including whether case and accents matter. On a case-insensitive collation, IN ('sales') matches 'Sales'. On a case-sensitive one, it does not. The earlier chapter on case sensitivity describes the differences between databases.
Combining IN with other predicates
IN is a single predicate, so you can combine it with AND and OR like any other condition.
SELECT id, name, department, salary
FROM employees
WHERE department IN ('Sales', 'Support')
AND salary >= 40000;Writing the same condition without IN shows why it helps readability. You would need parentheses around the OR group:
SELECT id, name, department, salary
FROM employees
WHERE (department = 'Sales' OR department = 'Support')
AND salary >= 40000;If you leave out those parentheses, AND binds more tightly than OR, and the query means something different:
-- Wrong: this reads as department = 'Sales'
-- OR (department = 'Support' AND salary >= 40000)
SELECT id, name, department, salary
FROM employees
WHERE department = 'Sales'
OR department = 'Support'
AND salary >= 40000;This version returns every Sales employee regardless of salary. Using IN removes this class of mistake, because the whole membership test is one predicate.
How NULL interacts with IN
NULL represents a missing or unknown value. Comparing anything to NULL with = gives unknown, not true. SQL uses three-valued logic, with true, false, and unknown, and WHERE keeps only rows whose predicate is true.
This has two consequences for IN.
- A row whose column value is
NULLis never matched byIN, even if the list containsNULL. The testNULL = NULLis unknown, not true. - A
NULLin the list never causes a match, but it also does not stop other values from matching.
SELECT id, name, department
FROM employees
WHERE department IN ('Sales', NULL);This returns the Sales employees only. The NULL item contributes nothing. Employees whose department is NULL are not returned.
To include rows with a missing value, test for it explicitly with IS NULL:
SELECT id, name, department
FROM employees
WHERE department IN ('Sales', 'Support')
OR department IS NULL;For plain IN, a NULL in the list is mostly harmless. The negated form, NOT IN, behaves very differently when the list contains NULL, and it can return no rows at all. The chapter on NOT IN explains this in detail.
IN with a subquery
The list can come from a query instead of being typed out. The subquery must return a single column.
SELECT id, name
FROM employees
WHERE department_id IN (
SELECT id
FROM departments
WHERE location = 'Berlin'
);This is useful when the list of values changes over time or is too long to write by hand. The next chapter covers subqueries with IN in more depth. For now, remember two points:
- The subquery is evaluated by the database, and you do not need to run it separately.
- An
INsubquery can often be rewritten as a join or anEXISTStest. Modern optimizers usually produce an equivalent plan for these forms.
Working with long lists
Applications often build IN lists from user selections, such as the ids of ticked checkboxes. Three issues come up.
- Size limits. Databases cap the number of items in a list or the number of bind parameters in a statement. The exact limits vary, and some are in the thousands or tens of thousands. If your list might be very large, load the values into a temporary table and use
IN (SELECT ...)or a join. - Parameterization. Never build the list by concatenating user input into the SQL text. Use one placeholder per value, for example
IN (?, ?, ?), and generate the right number of placeholders in your code. Some drivers and databases also accept an array parameter, with syntax that varies by system. - Empty lists. If the user selects nothing, the generated SQL
IN ()is invalid. Handle the empty case in your application, either by skipping the query or by adding a condition that is always false.
import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE employees (id INTEGER, name TEXT, department TEXT)")
conn.executemany(
"INSERT INTO employees VALUES (?, ?, ?)",
[(1, "Ana", "Sales"), (2, "Ben", "Support"), (3, "Cleo", "Legal")],
)
wanted = ["Sales", "Support"]
if wanted:
placeholders = ", ".join("?" for _ in wanted)
sql = f"SELECT id, name FROM employees WHERE department IN ({placeholders})"
rows = conn.execute(sql, wanted).fetchall()
else:
rows = []
print(rows)The code inserts the placeholders into the SQL text, but the values themselves travel separately as parameters. This keeps the query safe from SQL injection.
Performance notes
A column compared with IN against a short list of constants can usually use an index on that column. The database looks up each value in the list separately. Wrapping the column in a function, as in WHERE UPPER(department) IN (...), normally prevents ordinary index use, for the same reason as with LIKE. Very long lists can make planning slower, so the temporary table approach is often better for hundreds or thousands of values.
Common errors
| Mistake | Result | Fix |
|---|---|---|
| `IN ()` with no values | Syntax error | Handle the empty case in application code |
| `name IN ('A%')` | Matches only the literal text `A%` | Use `LIKE` with `OR` |
| Expecting `IN (NULL)` to find null rows | Returns no rows | Use `IS NULL` |
| Mixing `OR` and `AND` without parentheses | Wrong rows returned | Use `IN` or add parentheses |
| Subquery returns more than one column | Error | Select exactly one column |
| Comparing a timestamp column to a date with `IN` | Misses rows with a time part | Use a half-open range |
Exercise
A table tickets has a column status that holds 'open', 'closed', 'pending', or NULL. You run SELECT id FROM tickets WHERE status IN ('open', 'pending', NULL);. Which rows are returned, and how would you change the query to include tickets with no status as well?
Show answer
The query returns tickets whose status is 'open' or 'pending'. The NULL in the list never produces a true comparison, and rows with a NULL status are not matched because NULL = NULL is unknown. To include them, drop the NULL from the list and add an explicit test: WHERE status IN ('open', 'pending') OR status IS NULL.
Exercise
Rewrite this query using IN so that the intent is clear and no parentheses are needed: SELECT * FROM employees WHERE department = 'Sales' OR department = 'Support' OR department = 'Legal';
Show answer
SELECT * FROM employees WHERE department IN ('Sales', 'Support', 'Legal');