SQL from Scratch · Day 12 of 60 ·

AND, OR and NOT

Real questions often have more than one condition. Bags under 2,000. Customers in Lisbon or Hyderabad. AND, OR and NOT let you say that in one query.

AND needs both conditions to be true:

SELECT name, price
FROM products
WHERE category = 'Bags' AND price < 2000;

OR needs at least one to be true:

SELECT name, city
FROM customers
WHERE city = 'Lisbon' OR city = 'Hyderabad';

NOT flips a condition:

SELECT order_id, status
FROM orders
WHERE NOT status = 'Delivered';

The classic trap is mixing them, because AND is evaluated before OR. Use brackets to say what you mean:

SELECT name, price
FROM products
WHERE (category = 'Bags' OR category = 'Suits')
AND price < 2000;

Without the brackets, the price limit would apply to suits only.

Go deeper: SQLite expressions

Do you add brackets even when they aren't strictly needed?

Join the conversation on LinkedIn