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;
titleage_ratingprice
Cube Logic35
Word Quest710
Bakery Story315
Ocean Deep715
Pixel Racer315

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;
titleage_ratingprice
Lost Temple1220
Ocean Deep715

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 error

Write 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_idstarscomment
25Best RPG I have played in years!
85NULL
14Great 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:

titleage_ratingprice
Goal Rush350
Ice Hockey Pro345
Galaxy Trader1235
Star Pilots1235

Start programming for free

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

Or sign up with:

4/11