Comparison Operators
Besides =, SQL has five more comparison operators:
| Operator | Meaning | Example |
|---|---|---|
| = | equals | price = 30 |
| <> or != | doesn't equal | price <> 30 |
| < | is less than | price < 30 |
| > | is greater than | price > 30 |
| <= | is less than or equal to | price <= 30 |
| >= | is greater than or equal to | price >= 30 |
<> and != mean the same. <> is the one from the SQL standard, which every database knows; != you may know from other programming languages. This course uses <>.
Watch the boundary. “Cheaper than $15” is price < 15, and the games that cost exactly $15 aren't in it:
SELECT title, price
FROM games
WHERE price < 15
ORDER BY price;| title | price |
|---|---|
| Cube Logic | 5 |
| Word Quest | 10 |
“$15 at most” is price <= 15, and the three games for $15 are in it too:
SELECT title, price
FROM games
WHERE price <= 15
ORDER BY price, title;| title | price |
|---|---|
| Cube Logic | 5 |
| Word Quest | 10 |
| Bakery Story | 15 |
| Ocean Deep | 15 |
| Pixel Racer | 15 |
Either side of a comparison can also be a calculation. A customer has $50 and wants two copies of the same game, one for a friend. The games whose two copies cost $50 at most, the most expensive first:
SELECT title, price * 2 AS two_copies
FROM games
WHERE price * 2 <= 50
ORDER BY price DESC, title;| title | two_copies |
|---|---|
| Mystery Manor | 50 |
| Shadow Ninja | 50 |
| Tiny Kingdoms | 50 |
| … | … |
Typical mistake: the signs the other way round, => instead of >=. WHERE price => 40 ends with an error:
Error on line 1: near ">": syntax errorThe equals sign always comes second, in the same order as you say it: “greater than or equal to”.
Instructions
Show the title and the price of the games that cost $40 or more, the most expensive first. Sort the games with the same price by title:
| title | price |
|---|---|
| Knight's Oath | 60 |
| Goal Rush | 50 |
| Ice Hockey Pro | 45 |
| Dragon Forge | 40 |
| Robot Rebellion | 40 |
Below it, show the title and the age rating of the games that aren't suitable from the age of 3 (their age_rating isn't 3). Sort them by the age rating, from the lowest, and then by title:
| title | age_rating |
|---|---|
| Ocean Deep | 7 |
| Tiny Kingdoms | 7 |
| Word Quest | 7 |
| Castle Siege | 12 |
| … | … |
And for the accounts: show the order items for which the customer paid more than $50 in total, that is, those whose quantity * price is more than 50. Show the columns order_id and game_id, and the total named total, sorted by order_id:
| order_id | game_id | total |
|---|---|---|
| 22 | 14 | 60 |
| 26 | 15 | 60 |
| 27 | 15 | 60 |
| 29 | 15 | 60 |
Start programming for free
2/12