SQL Tutorial · SQL Basics · Lesson 5 of 36
SQL AND, OR, NOT
Combine conditions and control precedence with parentheses.
AND and OR
AND— both conditions must be true.OR— at least one must be true.
SELECT name, price, stock FROM products WHERE price < 50 AND stock > 20;
SELECT name, country FROM customers WHERE country = 'Japan' OR country = 'Netherlands';
Output
name | price | stock SQL for Beginners | 29.99 | 40 Wireless Mouse | 24.99 | 60 USB-C Hub | 39.95 | 30 Coffee Mug | 12 | 100 Rubber Duck | 5.5 | 200 name | country Guido van Rossum | Netherlands Yukihiro Matsumoto | Japan
Parentheses matter
AND is evaluated before OR. Use parentheses to say what you mean:
-- Electronics OR books, and only if in stock:
SELECT name, category_id, stock FROM products
WHERE (category_id = 1 OR category_id = 2) AND stock > 0;
Output
name | category_id | stock SQL for Beginners | 1 | 40 Clean Code | 1 | 15 Mechanical Keyboard | 2 | 25 Wireless Mouse | 2 | 60 4K Monitor | 2 | 8 USB-C Hub | 2 | 30
NOT
NOT negates a condition: NOT status = 'cancelled', NOT IN (...), NOT LIKE ..., IS NOT NULL.
SELECT order_id, status FROM orders WHERE NOT status IN ('delivered', 'cancelled');
Output
order_id | status 4 | shipped 8 | shipped 9 | pending 11 | pending
Test yourself
Which is evaluated first without parentheses: AND or OR?
ANDORWhichever comes firstNeither
Show answer
Answer: AND