mahir_data
Chapters0 / 26 completed

Chapter 05 · basic · 6 min

AND, OR, NOT: combining conditions

One condition in WHERE gets you far, but real questions usually need more than one: "delivered and over RM 100", "cancelled or pending". AND, OR, and NOT are how you combine and invert conditions.

We'll keep using the orders table.

The dataset

The same `orders` table: customer, total, and status.

AND: every condition must hold

Chain conditions with AND and a row only qualifies if all of them are true:

customertotalstatus
Aisyah120.00delivered
Chong310.00delivered

Delivered AND over RM 100

Editable, try changing it

OR: any condition will do

OR is looser: a row qualifies if at least one condition is true:

customerstatus
Balacancelled
Devipending
Faridpending

Cancelled OR pending

Editable, try changing it

Mixing AND and OR needs parentheses

Without parentheses, SQL evaluates AND before OR, the same precedence rule as multiplication before addition. That can silently change what you meant to ask. The parenthesized version below correctly reads as "(pending or cancelled) but only if over RM 100", and returns just one row:

customertotalstatus
Farid210.00pending

Drop the parentheses and SQL reads it as "pending, OR (cancelled and over RM 100)", a completely different, and wrong, question. This exact mistake is one of the most common silent bugs in real reporting queries: it never errors, it just quietly answers a different question than the one you intended.

Parentheses force the OR to group first

Editable, try changing it

NOT: reverse a condition

NOT flips a condition's truth value. On a simple equality check it's just a style choice (NOT (status = 'cancelled') behaves like status <> 'cancelled'), but it earns its keep in front of IN, BETWEEN, and LIKE next, since none of those have a separate <>-style shortcut:

customerstatus
Aisyahdelivered
Chongdelivered
Devipending
Faridpending

Everything except cancelled

Editable, try changing it

If you've used Excel or Google Sheets

The logic is identical to spreadsheet formulas: AND(status="delivered", total>100) and OR(status="cancelled", status="pending") are literally the same functions with the same names. The one thing SQL adds that a spreadsheet formula usually doesn't force you to think about is precedence. Get in the habit of parenthesizing any time you mix AND and OR in the same condition, even when you're fairly sure you know how it'll be read.

Ready to practice? Zalora's order filter question below combines AND, OR, and NOT on a slightly larger dataset.

Once you're comfortable chaining conditions, the next step is a shortcut for the common case of "one column, several acceptable values": IN, plus its range-based cousin, BETWEEN.

Sign in to track your progress.

Now practise it

Questions in the bank that drill this chapter's concept: