One condition is often not enough. "Members from Canada" is two conditions: the country is CA, and the customer is a member.
AND, OR, NOT
| Keyword | The row stays when |
|---|---|
a AND b | both conditions are true |
a OR b | at least one condition is true |
NOT a | the condition is false |
sql
SELECT name, city
FROM customers
WHERE country = 'CA' AND is_member = true;customers
| id | name | country | is_member |
|---|---|---|---|
| 1 | Ava Chen | CA | true |
| 2 | Liam Patel | CA | false |
| 3 | Sofia Rossi | IT | true |
| 8 | Omar Haddad | CA | true |
NOT country = 'CA' keeps the same rows as country <> 'CA'.
AND before OR
A condition with AND and OR is not read from left to right. AND is done first:
text
country = 'US' OR country = 'CA' AND is_member = true
is read as
country = 'US' OR (country = 'CA' AND is_member = true)That keeps every US customer, and the Canadian members. To get the members from the US or Canada, put the OR in parentheses:
customers
| id | name | country | is_member |
|---|---|---|---|
| 1 | Ava Chen | CA | true |
| 2 | Liam Patel | CA | false |
| 4 | Noah Kim | US | false |
| 5 | Mia Johnson | US | true |
| 8 | Omar Haddad | CA | true |
customers
| id | name | country | is_member |
|---|---|---|---|
| 1 | Ava Chen | CA | true |
| 2 | Liam Patel | CA | false |
| 4 | Noah Kim | US | false |
| 5 | Mia Johnson | US | true |
| 8 | Omar Haddad | CA | true |
Parentheses are done first. Use them every time a condition has both AND and OR. The query is then clear to every reader.