VillageSQL is a drop-in replacement for MySQL with extensions.
All examples on this page work on VillageSQL. Install Now →
AND, OR and NOT join conditions
together so that a single WHERE can ask a compound question.
Open the client with mysql -u root -p sakila before you start.
How AND, OR and NOT work
COLUMN_LIST with the columns you want, TABLE_NAME with the table,
and each of FIRST_CONDITION and SECOND_CONDITION with a test of its own.
AND keeps a row only when both conditions are true. OR keeps a row when at
least one is true. NOT reverses the condition that follows it.
They do not all bind equally. Of the 3, NOT binds tightest, then AND, then
OR. The server therefore reads a OR b AND c as a OR (b AND c), which is
rarely what someone writing it meant. Parentheses override that, and they cost
nothing.
All 3 bind more loosely than a comparison, which is why NOT rating = 'G'
below reverses the whole comparison rather than just the column.
Examples
1) Both conditions
G and run over 180 minutes.
2) Either condition
3) Reverse a condition
NOT rating = 'G' and rating <> 'G' select the same rows. Prefer <> for a
single comparison and keep NOT for reversing something larger.
AND binds tighter than OR
This looks like “rated G or PG, and over 180 minutes”.AND bound to the pair next to
it, so the server answered “rated G, or else rated PG and over 180 minutes”.
Every G film qualified on the first branch alone, whatever its length.
Parentheses say what was meant.
AND and OR as you write it.
OR does not take a bare second value
rating = 'G' OR 'PG' reads in English as “rated G or PG”. To the server it is
2 separate conditions, and the second one is the string 'PG' standing alone.
G films came back, and the footer reports a warning. Run SHOW WARNINGS
in the same session and the server explains itself:
Warning 1292 Truncated incorrect DOUBLE value: 'PG'.
A condition has to be true or false, so the server converted 'PG' to a
number. 'PG' starts with no digit, which converts to 0, which is false. The
whole second branch was therefore dead. Name the column on both sides, or use
IN.
NOT reverses only what comes next
NOT took the comparison beside it, so this is “not rated G, and over 180
minutes”. To reverse the whole pair, bracket it.
ACE GOLDFINGER is rated G and runs 48 minutes. It fails the bracketed pair,
so reversing the pair keeps it.
Summary
- Use
ANDwhen every condition must hold, andORwhen any one will do. - Bracket any
WHEREthat mixesANDandOR, becauseANDbinds tighter. - Expect
NOTto reverse only the condition beside it. - Repeat the column on both sides of
OR, because a bare value converts to a number. - Watch the warning count in the footer, then run
SHOW WARNINGS.

