Combining Conditions with AND
One condition is often not enough. A parent is looking for a game for their 7-year-old, and it should cost less than $20. Join the two conditions with AND:
SELECT title, age_rating, price
FROM games
WHERE age_rating <= 7
AND price < 20
ORDER BY price, title;| title | age_rating | price |
|---|---|---|
| Cube Logic | 3 | 5 |
| Word Quest | 7 | 10 |
| Bakery Story | 3 | 15 |
| Ocean Deep | 7 | 15 |
| Pixel Racer | 3 | 15 |
A row gets into the result only when both conditions are true for it. Cube Logic is suitable from the age of 3 and costs $5: both conditions are true, so it's in. Goal Rush is suitable from 3 too, but it costs $50: the second condition is false, so it's left out.
You can join as many conditions as you need, and a row must meet all of them. Put each condition on its own line, with AND at the start, and even a long condition is easy to read. The adventure games for 12-year-olds for $20 at most:
SELECT title, age_rating, price
FROM games
WHERE genre = 'Adventure'
AND age_rating <= 12
AND price <= 20
ORDER BY title;| title | age_rating | price |
|---|---|---|
| Lost Temple | 12 | 20 |
| Ocean Deep | 7 | 15 |
A range of values, such as the prices from $10 to $20, is two conditions joined with AND too: price >= 10 AND price <= 20. (A shorter way is coming later in this lesson.)
Typical mistake: WHERE price >= 10 AND <= 20. You'd say “a price of at least 10 and at most 20”, but in SQL, each condition must be complete on its own. The second one here has no column, and SQLite reports:
Error on line 1: near "<=": syntax errorWrite the column in each condition: price >= 10 AND price <= 20.
Instructions
Show the customer ID, the stars and the comment of the reviews of the game with ID 1 (game_id) that have at least 4 stars. Sort them by stars, from the most, and then by customer ID:
| customer_id | stars | comment |
|---|---|---|
| 2 | 5 | Best RPG I have played in years! |
| 8 | 5 | NULL |
| 1 | 4 | Great story, a bit long. |
Below it, show the title, the age rating and the price of the games suitable for a 12-year-old (age rating 12 at most) that cost at least $35. The most expensive first, and games with the same price by title:
| title | age_rating | price |
|---|---|---|
| Goal Rush | 3 | 50 |
| Ice Hockey Pro | 3 | 45 |
| Galaxy Trader | 12 | 35 |
| Star Pilots | 12 | 35 |
Start programming for free
4/12