WHERE: picking the rows you need
038 min
Usually you do not need every row of a table. “Only 2nd-year students”, “products cheaper than 100,000” — conditions like these are written with WHERE.
The pattern
SELECT columns FROM table WHERE condition;The database checks every row: if the condition is true, the row goes into the result; if not, it is left out.
Comparison operators
| Operator | Meaning | Example |
|---|---|---|
= |
equal | course = 2 |
<> or != |
not equal | city <> 'Toshkent' |
> / < |
greater / less | salary > 9000000 |
>= / <= |
greater or equal / less or equal | score >= 86 |
Text and dates go in quotes
Numbers are written without quotes; text and dates go in single quotes:
Forget the quotes and the database takes Samarqand for a column name and complains that there is no such column. Dates are written as 'year-month-day':
Several conditions: AND, OR, NOT
AND— both conditions must hold;OR— at least one must hold;NOT— turns a condition around.
When you mix AND and OR, use brackets — otherwise AND is applied first and the result may not be what you expect:
Show first_name and last_name of the students who study on a grant (funding = 'grant').
Show first_name and city of the 3rd-year students who are not from Tashkent (city is not 'Toshkent').
Remember
WHEREpicks rows by a condition.- Text and dates go
'in single quotes', numbers go without. - Mixing
ANDandOR? Use brackets.