CodeMIRAI
0 XP

AND, OR, IN and BETWEEN

2 min read 9 runnable examples Quiz included

A WHERE with one condition answers simple questions. Real questions usually need several.

AND: every condition must be true

SQL
SELECT name, category, price
FROM products
WHERE category = 'Accessories' AND price < 40;

Only accessories that also cost under 40 qualify. The keyboard is an accessory, but at 89.99 it fails the second test.

OR: at least one condition must be true

SQL
SELECT name, city, country
FROM customers
WHERE country = 'India' OR country = 'Japan';

NOT: reverse a condition

SQL
SELECT name, country
FROM customers
WHERE NOT country = 'India';

WHERE NOT country = 'India' means the same as WHERE country <> 'India'.

Mixing AND and OR

AND is evaluated before OR, the way multiplication comes before addition. That catches everyone out at least once. Suppose you want Office or Audio products under 100:

SQL
-- wrong: this means Office (any price) OR (Audio under 100)
SELECT name, category, price
FROM products
WHERE category = 'Office' OR category = 'Audio' AND price < 100;

The 349 chair sneaks in. Parentheses say what you mean:

SQL
SELECT name, category, price
FROM products
WHERE (category = 'Office' OR category = 'Audio') AND price < 100;

IN: match any value in a list

A chain of ORs on the same column is shorter with IN:

SQL
SELECT name, country
FROM customers
WHERE country IN ('India', 'Japan', 'UK');

NOT IN excludes the list:

SQL
SELECT order_id, status
FROM orders
WHERE status NOT IN ('delivered', 'cancelled');

BETWEEN: a range

BETWEEN low AND high includes both ends:

SQL
SELECT name, price
FROM products
WHERE price BETWEEN 30 AND 100
ORDER BY price;

It works for dates written as YYYY-MM-DD too, because that format sorts correctly as text:

SQL
SELECT order_id, order_date, status
FROM orders
WHERE order_date BETWEEN '2024-06-10' AND '2024-06-20';
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.