Skip to content

SQL IN Operator

IN checks whether a value is one of a list. It is a shorter way of writing several conditions joined by OR.

SELECT column1, column2
FROM table_name
WHERE column1 IN (value1, value2, value3);

The examples use the tables from the example database.

The productions made in Ireland or Canada:

SELECT Title, Country
FROM Productions
WHERE Country IN ('Ireland', 'Canada');
Title Country
Saltmarsh Ireland
Fennick’s Return Canada

This is the same as WHERE Country = 'Ireland' OR Country = 'Canada', and easier to read as the list grows.

NOT IN keeps the rows whose value is not in the list. Everything that is neither a drama series nor a documentary:

SELECT Title, Format
FROM Productions
WHERE Format NOT IN ('Drama series', 'Documentary');
Title Format
Quarry Lane Feature film
Saltmarsh Feature film

The list can come from a query of its own, called a subquery. The productions that have at least one unpaid invoice:

SELECT Title
FROM Productions
WHERE ProductionID IN (
SELECT ProductionID FROM Invoices WHERE PaidDate IS NULL
);
Title
The Lantern Keepers
Six Bells

The subquery finds the ProductionID of each unpaid invoice, 1 and 4, and the outer query keeps the productions with those IDs.

If the list behind NOT IN contains a NULL, no row passes at all. To find the crew members who manage nobody, you might ask for the people whose ID never appears in ReportsTo:

SELECT Name
FROM Crew
WHERE CrewID NOT IN (SELECT ReportsTo FROM Crew);

This returns nothing, because some ReportsTo values are NULL, and a comparison with NULL is never true (see SQL Null). Leave the NULLs out of the subquery and the answer appears:

SELECT Name
FROM Crew
WHERE CrewID NOT IN (
SELECT ReportsTo FROM Crew WHERE ReportsTo IS NOT NULL
);
Name
Priya Nair
Owen Price
Lucy Brennan
Sam Ellis

NOT EXISTS avoids the trap altogether, and is often the better choice for this kind of question.