VillageSQL is a drop-in replacement for MySQL with extensions.
All examples on this page work on VillageSQL. Install Now →
IN tests one column against several values at once. It says what a chain of
OR says, in one clause, and it is the clause most people reach for once a
filter grows past 2 values.
Open the client with mysql -u root -p sakila before you start.
How IN works
COLUMN_NAME with the column to test, and FIRST_VALUE and
SECOND_VALUE with the values to accept.
The condition is true when the column equals any value in the brackets. Separate
the values with commas, and use as many as you need.
x IN (a, b) means the same as x = a OR x = b. Write whichever reads better,
and expect IN to read better past 2 values.
Examples
1) Match any of several values
2) Match none of them
3) A list of numbers
actor_id order because
ORDER BY asked for it, not because the list is in that order.
4) A list the server works out for itself
The brackets can hold a query instead of a list.film_actor is the table that
pairs each film with each actor in it, so this asks for the films actor 1
appears in, without you knowing any film id.
IN list is where most people
first write one.
A NULL in the list breaks NOT IN
IN and NOT IN do not treat a NULL in the list the same way, and neither one
warns you.
With IN, a NULL in the list is harmless. A row that matches a real value is
still kept.
NOT IN, the same list returns nothing at all.
G, so an empty result
is a surprise. The reason is that NOT IN asks whether the column differs from
every value in the list, and nothing can be shown to differ from NULL.
Comparing anything to NULL gives NULL rather than true or false, so the whole
condition is never true and no row survives.
This matters most when the list is a subquery, because a subquery you did not
write by hand can return a NULL you did not expect. Add
WHERE COLUMN_NAME IS NOT NULL inside the subquery when that is possible. The
IS NULL lesson covers how NULL compares.
Summary
- Use
INto test one column against a list of values in one clause. - Read
x IN (a, b)asx = a OR x = b. - Quote strings in the list and leave numbers bare.
- Put a subquery in the brackets when the list is itself an answer.
- Keep NULL out of a
NOT INlist, because it returns no rows at all.
See also
- AND, OR and NOT — the OR chain IN replaces
- IS NULL — why comparing to NULL is neither true nor false
- BETWEEN — testing a range rather than a list
- Subqueries — the query form used in example 4

