IN checks whether a value is one of a list. It is a shorter way of writing several conditions joined by OR.
SELECT column1, column2FROM table_nameWHERE column1 IN (value1, value2, value3);The examples use the tables from the example database.
A list of values
Section titled “A list of values”The productions made in Ireland or Canada:
SELECT Title, CountryFROM ProductionsWHERE 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, FormatFROM ProductionsWHERE Format NOT IN ('Drama series', 'Documentary');| Title | Format |
|---|---|
| Quarry Lane | Feature film |
| Saltmarsh | Feature film |
The results of another query
Section titled “The results of another query”The list can come from a query of its own, called a subquery. The productions that have at least one unpaid invoice:
SELECT TitleFROM ProductionsWHERE 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.
A trap with NOT IN
Section titled “A trap with NOT IN”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 NameFROM CrewWHERE 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 NameFROM CrewWHERE 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.