CPCODELAB
SQL

AND, OR, NOT — Combining Conditions

7 min read

Combining Conditions

Real-world queries often need more than one condition. SQL provides AND, OR, and NOT to combine conditions in the WHERE clause.

sql
-- Students from Mumbai who are older than 20
SELECT name FROM students
WHERE city = 'Mumbai' AND age > 20;

-- Students from Delhi OR Bengaluru
SELECT name, city FROM students
WHERE city = 'Delhi' OR city = 'Bengaluru';

-- Students NOT from Chennai
SELECT name FROM students
WHERE NOT city = 'Chennai';

When mixing AND and OR, wrap OR groups in parentheses to make precedence explicit. AND has higher precedence than OR in SQL, which can produce surprising results if you omit parentheses.

sql
-- Correct: students from Mumbai who are 18+ OR students from Pune
SELECT name FROM students
WHERE (city = 'Mumbai' AND age >= 18) OR city = 'Pune';

When in doubt, add parentheses. They cost nothing and make the query's intent obvious to every reader.

Ready to test yourself?
Practice SQL— quiz & coding exercises