IN / NOT IN in SQL
Match against a list of values
IN tests a column against a comma-separated list — department IN ('Sales', 'Marketing') is exactly department = 'Sales' OR department = 'Marketing', just shorter and faster to read. NOT IN flips it. The list can also come from a subquery, making IN the workhorse of semi-joins.
List the candidates
department IN ('Sales', 'Marketing') — values in parentheses, comma-separated, quotes for text.
It is sugar for ORs
Exactly department = 'Sales' OR department = 'Marketing' — same plan, far less typing, harder to misplace a parenthesis.
NOT IN flips it
Keeps every row outside the list.
The list can be a query
WHERE dept_id IN (SELECT dept_id FROM active_departments) — a semi-join in disguise.
Respect the NULL trap
If the list contains NULL, NOT IN returns zero rows — filter NULLs out first or use NOT EXISTS.
1SELECT name, department2FROM employees3WHERE department IN ('Sales', 'Marketing');
| name | department |
|---|---|
| Bob | Sales |
| David | Marketing |
| Elena | Sales |
Three rows match the two-item list — same result as the OR chain, one third of the typing. Tick departments in/out of the list in the visualization.
IN with a list
Membership over an OR chain.
1SELECT name, department2FROM employees3WHERE department IN ('Sales', 'Marketing');
| name | department |
|---|---|
| Bob | Sales |
| David | Marketing |
| Elena | Sales |
NOT IN
The complement of membership.
1SELECT name, department2FROM employees3WHERE department NOT IN ('Sales', 'Marketing');
| name | department |
|---|---|
| Alice | Engineering |
| Cynthia | Engineering |
| Farid | Engineering |
Numbers in a list
IDs and codes, unquoted.
1SELECT name FROM employees2WHERE id IN (1, 3, 6);
| name |
|---|
| Alice |
| Cynthia |
| Farid |
NOT IN + NULL = zero rows
The famous three-valued-logic ambush.
1SELECT name FROM employees2WHERE department NOT IN ('Sales', NULL);3-- returns NOTHING, not the non-Sales rows!
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Take the queries you just visualized and see the data structures that power real databases.