Labs ICT
Pro Login

AND & OR

Real-world queries almost never have just one condition. You usually need to combine multiple filters. That is where AND and OR come in.

AND — All Conditions Must Be True

Use AND when you want rows that satisfy every condition:

-- Students from Kano who scored above 80
SELECT * FROM students WHERE city = 'Kano' AND score > 80;

Only rows that match BOTH conditions will show up. If a student is from Kano but scored 70, they are out. If a student scored 90 but is from Lagos, also out.

OR — At Least One Condition Must Be True

Use OR when you want rows that match any of the conditions:

-- Students from Kano OR students who scored above 80
SELECT * FROM students WHERE city = 'Kano' OR score > 80;

This gives you a bigger result set because either condition is enough to include a row.

Combining AND and OR

Here is where it gets tricky. When you mix AND and OR, you need parentheses to make sure SQL understands what you mean:

-- Students from Kano OR Abuja, who scored above 80
SELECT * FROM students WHERE (city = 'Kano' OR city = 'Abuja') AND score > 80;

Without the parentheses, SQL would evaluate AND first (it has higher precedence), and you would get a completely different result. When in doubt, use parentheses. I use them even when I am not sure I need them. Better safe than sorry.