Parentheses and NOT
When a condition has both AND and OR, it matters which of them goes first. Say you want the sports or racing games that cost less than $20, and you write:
SELECT title, genre, price
FROM games
WHERE genre = 'Sports' OR genre = 'Racing' AND price < 20
ORDER BY title;| title | genre | price |
|---|---|---|
| Goal Rush | Sports | 50 |
| Ice Hockey Pro | Sports | 45 |
| Pixel Racer | Racing | 15 |
Goal Rush costs $50, so why is it there? AND goes before OR, just as multiplication goes before addition in math. SQLite first joins genre = 'Racing' AND price < 20, and only then adds OR genre = 'Sports'. So the query has found the racing games under $20 and all the sports games, whatever their price.
To make OR go first, put it in parentheses, as in math:
SELECT title, genre, price
FROM games
WHERE (genre = 'Sports' OR genre = 'Racing') AND price < 20
ORDER BY title;| title | genre | price |
|---|---|---|
| Pixel Racer | Racing | 15 |
Now every game must be a sports or a racing game, and also cost less than $20. Whenever a condition mixes AND and OR, use parentheses: you won't have to remember which goes first, and whoever reads the query will see at once what you meant.
NOT in front of a condition turns it around: it's true where the condition is false, and the other way round. NOT price < 20 is the same as price >= 20. It's most useful in front of parentheses, where it turns around the whole condition inside them. The games that are neither sports nor racing games:
SELECT title, genre
FROM games
WHERE NOT (genre = 'Sports' OR genre = 'Racing')
ORDER BY title;| title | genre |
|---|---|
| Bakery Story | Simulation |
| Castle Siege | Strategy |
| Cube Logic | Puzzle |
| … | … |
Without the parentheses, NOT would turn around only the first condition: NOT genre = 'Sports' OR genre = 'Racing' finds all the games that aren't sports games, the racing ones included.
Instructions
The query in the editor should show the paid orders of the customers with ID 6 and 8, but it shows a refunded order too. Add parentheses, so that it shows only the paid orders of these two customers:
| id | customer_id | status |
|---|---|---|
| 10 | 8 | paid |
| 12 | 6 | paid |
| 25 | 6 | paid |
Below it, add a query for a page for older players: every game except the cheap games for small children. The cheap games for small children are those suitable from the age of 3 that cost less than $20. Write this condition in parentheses and turn it around with NOT. Show the title, the age rating and the price, sorted by price and then by title. The result starts like this:
| title | age_rating | price |
|---|---|---|
| Word Quest | 7 | 10 |
| Ocean Deep | 7 | 15 |
| Lost Temple | 12 | 20 |
| Moon Farm | 3 | 20 |
| … | … | … |
Start programming for free
6/11