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;
titlegenre
Dragon ForgeRPG
Knight's OathRPG
Bakery StorySimulation
Moon FarmSimulation
……

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;
titleage_rating
Dragon Forge16
Knight's Oath16
Robot Rebellion16
Shadow Ninja16
Zombie Town18

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;
namecity
Isla YoungLeeds
Max BakerBristol
Mia LewisBristol
Noah WilsonLeeds
Oscar KingBristol

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:

nameemail
Grace Hallgrace.hall@mail.com
Liam Turnerliam.t@mail.com
Mia Lewismia.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:

titlegenre
Bakery StorySimulation
Castle SiegeStrategy
Cube LogicPuzzle
……

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

9/11