SQL AND, OR and NOT
AND, OR and NOT let you combine several conditions in one WHERE clause.
The AND Operator
AND keeps a row only when all conditions are true.
Example
SELECT name, city, marks
FROM students
WHERE city = 'Karachi' AND marks > 70;| name | city | marks |
|---|---|---|
| Ali Khan | Karachi | 78 |
Three students live in Karachi, but only Ali also has more than 70 marks. Hamza has exactly 70, which is not more than 70.
You can join more than two conditions:
Example
SELECT name
FROM students
WHERE city = 'Lahore' AND age > 20 AND marks > 86;| name |
|---|
| Sana Iqbal |
The OR Operator
OR keeps a row when at least one condition is true.
Example
SELECT name, city
FROM students
WHERE city = 'Lahore' OR city = 'Islamabad';| name | city |
|---|---|
| Ayesha Siddiqui | Lahore |
| Fatima Noor | Islamabad |
| Sana Iqbal | Lahore |
The NOT Operator
NOT turns a condition around. It keeps rows where the condition is false.
Example
SELECT name, city
FROM students
WHERE NOT city = 'Karachi';| name | city |
|---|---|
| Ayesha Siddiqui | Lahore |
| Fatima Noor | Islamabad |
| Sana Iqbal | Lahore |
NOT is also used in phrases you will meet later: NOT LIKE, NOT IN, NOT BETWEEN and IS NOT NULL.
How They Work
| Condition A | Condition B | A AND B | A OR B |
|---|---|---|---|
| true | true | true | true |
| true | false | false | true |
| false | true | false | true |
| false | false | false | false |
Mixing AND and OR: Use Brackets
AND is checked before OR, just like multiplication comes before addition in maths. This can give surprising results. Suppose you want students aged 21 or more who live in Karachi or Lahore:
Example
SELECT name, city, age
FROM students
WHERE (city = 'Karachi' OR city = 'Lahore') AND age >= 21;| name | city | age |
|---|---|---|
| Ayesha Siddiqui | Lahore | 21 |
| Bilal Ahmed | Karachi | 22 |
| Sana Iqbal | Lahore | 23 |
Without the brackets, the database would read it as city = 'Karachi' OR (city = 'Lahore' AND age >= 21), and every Karachi student would be returned, whatever their age.
Whenever you mix AND and OR, add brackets. Even when they are not strictly needed, they make your meaning clear to the next person who reads the query.
Exercise
Exercise
Which students does this query return? SELECT name FROM students WHERE city = 'Karachi' AND age < 19;
