Lists of Values with IN
When a column should equal one of several values, OR gets long: genre = 'RPG' OR genre = 'Simulation' OR genre = 'Strategy'. IN says the same more briefly. After the column comes IN and a list of values in parentheses, separated by commas:
SELECT title, genre
FROM games
WHERE genre IN ('RPG', 'Simulation', 'Strategy')
ORDER BY genre, title;| title | genre |
|---|---|
| Dragon Forge | RPG |
| Knight's Oath | RPG |
| Bakery Story | Simulation |
| Moon Farm | Simulation |
| … | … |
A row gets into the result when its value equals any of the values in the list. The order of the values doesn't matter, and the list can be as long as you need. Numbers go in the list without quotes:
SELECT title, age_rating
FROM games
WHERE age_rating IN (16, 18)
ORDER BY title;| title | age_rating |
|---|---|
| Dragon Forge | 16 |
| Knight's Oath | 16 |
| Robot Rebellion | 16 |
| Shadow Ninja | 16 |
| Zombie Town | 18 |
NOT IN is the opposite: it finds the rows whose value isn't in the list. The customers who aren't from London or Manchester:
SELECT name, city
FROM customers
WHERE city NOT IN ('London', 'Manchester')
ORDER BY name;| name | city |
|---|---|
| Isla Young | Leeds |
| Max Baker | Bristol |
| Mia Lewis | Bristol |
| Noah Wilson | Leeds |
| Oscar King | Bristol |
Ava Green and Henry Scott aren't in the result, even though they're not from London or Manchester: their city is NULL. Rows with NULL are found by neither IN nor NOT IN. You'll learn why in the last exercise of this lesson.
Typical mistake: one pair of quotes around the whole list. genre IN ('RPG, Strategy') isn't an error, but it finds nothing. The list has a single value, the text RPG, Strategy, and no game has such a genre. Each text in the list needs its own quotes: ('RPG', 'Strategy').
Instructions
The shop has drawn the winners of a prize: the customers with ID 2, 7 and 11. Show their name and email, sorted by name:
| name | |
|---|---|
| Grace Hall | grace.hall@mail.com |
| Liam Turner | liam.t@mail.com |
| Mia Lewis | mia.lewis@mail.com |
Below it, show the title and the genre of the games that aren't action, racing or sports games (the genres Action, Racing and Sports). Use NOT IN and sort the games by title. The result starts like this:
| title | genre |
|---|---|
| Bakery Story | Simulation |
| Castle Siege | Strategy |
| Cube Logic | Puzzle |
| … | … |
Start programming for free
9/12