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;
titlegenreprice
Goal RushSports50
Ice Hockey ProSports45
Pixel RacerRacing15

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;
titlegenreprice
Pixel RacerRacing15

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;
titlegenre
Bakery StorySimulation
Castle SiegeStrategy
Cube LogicPuzzle
……

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:

idcustomer_idstatus
108paid
126paid
256paid

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:

titleage_ratingprice
Word Quest710
Ocean Deep715
Lost Temple1220
Moon Farm320
………

Start programming for free

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

Or sign up with:

6/12