SQL IN and NOT IN
SQL IN keeps the rows whose value is in a list, like genre IN ('fantasy', 'drama'). NOT IN does the opposite and leaves those rows out.
The examples below use this books table. Change a query and press Run to see its result.
Table: books
| id | title | genre |
|---|---|---|
| 1 | Wonder | drama |
| 2 | Matilda | fantasy |
| 3 | Holes | adventure |
| 4 | The BFG | fantasy |
| 5 | Boy | memoir |
| 6 | Coraline | drama |
Keep rows whose value is in a list with IN
Write the column, then IN, then the values in brackets with commas between them. This query keeps the fantasy and drama books:
SELECT title, genreFROM booksWHERE genre IN ('fantasy', 'drama');The result has four books. genre IN ('fantasy', 'drama') keeps the same rows as genre = 'fantasy' OR genre = 'drama', and it is shorter.
Leave out rows with NOT IN
NOT IN keeps every row whose value is not in the list. Numbers in the list have no quotes. This query leaves out the books with id 2 and 5:
SELECT id, titleFROM booksWHERE id NOT IN (2, 5);The result has four books: every book except Matilda and Boy.
Use NOT IN as one condition among others
IN and NOT IN are each one condition, so they can follow another condition with AND. This query keeps the fantasy and drama books, then leaves out book 4:
SELECT id, title, genreFROM booksWHERE genre IN ('fantasy', 'drama') AND id NOT IN (4);Wonder, Matilda and Coraline are in the result. The BFG is fantasy, but NOT IN (4) leaves it out.
Note: Text values in the list need single quotes, just like with =.
See also: SQL OR.
Your turn
Add a WHERE line with NOT IN so the query shows every book except the ones with id 1, 3 and 6.
title ------- Matilda The BFG Boy (3 rows)
-- add a WHERE line after FROM, and move the ; to the endSELECT titleFROM books;