SQL Tutorial menu

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

sql
SELECT name, city, marks
FROM students
WHERE city = 'Karachi' AND marks > 70;
namecitymarks
Ali KhanKarachi78

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

sql
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

sql
SELECT name, city
FROM students
WHERE city = 'Lahore' OR city = 'Islamabad';
namecity
Ayesha SiddiquiLahore
Fatima NoorIslamabad
Sana IqbalLahore

The NOT Operator

NOT turns a condition around. It keeps rows where the condition is false.

Example

sql
SELECT name, city
FROM students
WHERE NOT city = 'Karachi';
namecity
Ayesha SiddiquiLahore
Fatima NoorIslamabad
Sana IqbalLahore

NOT is also used in phrases you will meet later: NOT LIKE, NOT IN, NOT BETWEEN and IS NOT NULL.

How They Work

Condition ACondition BA AND BA OR B
truetruetruetrue
truefalsefalsetrue
falsetruefalsetrue
falsefalsefalsefalse

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

sql
SELECT name, city, age
FROM students
WHERE (city = 'Karachi' OR city = 'Lahore') AND age >= 21;
namecityage
Ayesha SiddiquiLahore21
Bilal AhmedKarachi22
Sana IqbalLahore23

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;

Learn SQL with a teacher

Join the Full Stack Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp