AND, OR, NOT
A WHERE clause can test more than one thing at once. Join conditions with:
AND— both must be trueOR— at least one must be trueNOT— flips a condition
SELECT name FROM student WHERE form = '11A' AND score > 88;
This returns 11A students who also scored above 88.
When you mix AND and OR, use brackets to make the meaning clear, just like in maths:
SELECT name FROM student
WHERE form = '11B' AND (score < 70 OR score > 90);
AND is checked before OR, so without the brackets SQL would read this as (form = '11B' AND score < 70) OR score > 90, and Sara (95, form 11A) would get in too. The brackets make SQL check the score test as one unit.
Question. Show the name of each student who is in 11B, or in 11A, and who scored more than 90.
Without brackets AND goes first, so this means "in 11B, or (in 11A and over 90)":
SELECT name FROM student
WHERE form = '11B' OR form = '11A' AND score > 90;
name
Jamal
Sara
Tom
Jamal (72) and Tom (64) are wrong answers: they are in 11B but did not score over 90.
With brackets the form test is one unit, and the score test applies to everyone:
SELECT name FROM student
WHERE (form = '11B' OR form = '11A') AND score > 90;
name
Sara
- Repeat the column in each test.
WHERE form = '11A' OR '11B'does not mean "11A or 11B". Writeform = '11A' OR form = '11B'. - Mixing
ANDandORwithout brackets.ANDis checked first, which is often not what you meant. Add brackets. NOTgoes in front of the test it reverses:WHERE NOT form = '11A'.
AND, OR, NOT
Combine conditions with AND/OR/NOT — see the truth table.
Difficulty 2/5 · 140 coins + a small bonus on first completion today
Show the name of every student who is in form 11A and scored more than 88.
Click Run to see the output here.
Difficulty 2/5 · 140 coins + a small bonus on first completion today
Show the name of every student who is in form 11B or scored 95 or more.
Click Run to see the output here.
Difficulty 2/5 · 140 coins + a small bonus on first completion today
Show the name of every student who is not in form 11A. Use NOT in front of the test.
Click Run to see the output here.
Difficulty 2/5 · 140 coins + a small bonus on first completion today
The starter should list students in 11A or 11B who scored under 80, but it returns all five. AND is checked before OR. Add brackets so the form test is checked first.
Click Run to see the output here.