SQL and MySQL course Β· Module 3: Filtering (WHERE)
Comparison operators
In this lesson3
At the heart of every condition is a comparison of two values. The scribe asks: "Is the price greater than 30? Does the year of publication equal 1990?". In MySQL we answer such questions with comparison operators.
The six operators
| Operator | Meaning | Example |
|---|---|---|
= | equal | cena = 30 |
<> | not equal | kraj <> 'Polska' |
< | less than | rok_wydania < 1900 |
> | greater than | cena > 50 |
<= | less than or equal | cena <= 20 |
>= | greater than or equal | rok_wydania >= 2000 |
Note: in MySQL we check equality with a single = sign (not == as in JavaScript). Inequality is written as <>.
Example: expensive books
SELECT * FROM ksiazki
WHERE cena > 50;This means: "Show all books whose price exceeds 50 coins".
Less, greater and their "or equal" variants
The operators <= and >= also include the boundary value. The condition cena <= 20 returns both books cheaper than 20 coins and those costing exactly 20:
SELECT * FROM ksiazki
WHERE cena <= 20;And the condition rok_wydania >= 2000 also includes the year 2000 itself:
SELECT * FROM ksiazki
WHERE rok_wydania >= 2000;Remember a simple rule: a < or > sign without a line does not include the boundary, but with a line <= / >= it does include it. A small difference, but it can change the whole result!
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. Which operator do we use in MySQL to check whether two values are EQUAL?
2. Which notation means in MySQL that values are DIFFERENT (not equal)?
These are 2 of 3 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Code editor
Write a query that retrieves all columns from the ksiazki table only for those books whose cena is greater than 30.
- Code editor
Write a query that retrieves all columns from the ksiazki table for books whose cena is less than or equal to 20.
- Horizontal ordering
Arrange in one line the condition checking that the publication year is greater than or equal to 2000: