AND, OR & NOT
One condition answers “who is in grade 12?”. Real questions are fussier: in grade 12 and from Gangtok, or scoring below 70 or above 90. Two conditions joined by one word, and the word changes everything.
1AND — both must be true
Four students are in grade 12 and two live in Gangtok. Only the students who satisfy both come back — so and always gives you the same number of rows or fewer than either condition alone. Each extra and narrows the result.
2OR — either one will do
The very low scorers and the very high ones, in one resultset. A row qualifies if either side is true, so or always gives the same number of rows or more than either condition alone. Each extra or widens the result.
and; too few, and you probably wanted or.3Say the column name every time
In English you say “percent below 70 or above 90”. In SQL each side of the or must be a complete condition:
The second is a syntax error. > 90 on its own does not say what is greater than 90.
4NOT — reverse a condition
not goes in front of a condition and flips it:
For a simple comparison this is the same as using <>, and MySQL agrees — the query below returns the identical eight rows:
not earns its keep in front of the operators that have no symbol to negate — not between, not in and not like, all coming up in the next lessons.
5The trap: NOT does not rescue NULLs
Count those last two resultsets. Eight rows — but the table has twelve students and only two live in Gangtok. Twelve minus two is ten, not eight. Where did the other two go?
Sohan and Nima have NULL in city. Asking is your city Gangtok? about an unknown city gives NULL, and not NULL is still NULL — never true. So they fail both the condition and its opposite.
where city = 'Gangtok' (2 rows) and where city <> 'Gangtok' (8 rows) leave 2 rows in neither. To include them you must say so explicitly:where city <> 'Gangtok' or city is null6When you mix AND with OR
and is evaluated before or, exactly as × is evaluated before + in arithmetic. So this:
means grade 12, or (grade 11 from Singtam) — which is almost certainly not what was intended. Brackets make it say what you mean:
and and or appear in the same where, bracket the part you want done first.| Operator | Row is kept when | Effect on the row count |
|---|---|---|
| and | Both conditions are true | Same or fewer — it narrows |
| or | At least one is true | Same or more — it widens |
| not | The condition is false | Reverses — but NULL rows stay out |
Which returns students in grade 12 who are also from Singtam?
Why does where city <> 'Gangtok' return 8 rows when 12 students exist and only 2 are from Gangtok?
What does where a = 1 or a = 2 and b = 3 mean?