Stop 03 · Filtering DataTopics · 3/8

AND, OR, NOT and Operator Precedence

Part of the SQL Roadmap

In short

Real questions have several conditions: Delhi or Mumbai, paid, above ₹500. Combining them is easy, and getting them subtly wrong is even easier. Precedence is the reason.

AND, OR and NOT combine conditions. AND is evaluated before OR, so mixing them without parentheses is a classic source of wrong results.

The jaadu stands at a classroom blackboard, drawing big curved brackets around part of a long row of chalk symbols.

Think of it like this

BODMAS for conditions

In school maths, 2 + 3 × 4 is 14, not 20, because multiplication goes first. SQL has the same rule: NOT first, then AND, then OR. Just as brackets fix the maths, brackets in SQL make the logic do what you meant.

Watch it happen

How city = 'Delhi' OR city = 'Mumbai' AND status = 'paid' really groups

OR
city = 'Delhi'
AND
city = 'Mumbai'
status = 'paid'

1/4AND binds tighter, so it grabs its neighbours first: Mumbai AND paid.

The big ideas

What you need to know

AND: all must be true

Each extra AND narrows the result. A row must pass every condition.

OR: any can be true

Each extra OR widens the result. A row needs to pass just one condition.

NOT flips a condition

NOT status = 'paid' keeps rows that aren't paid. NOT also works with IN, BETWEEN, LIKE and EXISTS.

Order: NOT, AND, OR

When AND and OR appear together, always add brackets. It costs nothing and removes doubt.

See it in code

Walk through the code

sql
1-- Wrong: returns every Delhi order, paid or not2SELECT order_id, city, status3FROM orders4WHERE city = 'Delhi' OR city = 'Mumbai' AND status = 'paid';5 6-- Right: paid orders from either city7SELECT order_id, city, status8FROM orders9WHERE (city = 'Delhi' OR city = 'Mumbai')10  AND status = 'paid'11  AND NOT amount < 200;

1/3AND runs first, so this means Delhi OR (Mumbai AND paid).

Same words, different meaning. Precedence works the same way in PostgreSQL, MySQL and SQL Server.

Save yourself the pain

Common mistakes

Oops

WHERE city = 'Delhi' OR 'Mumbai'.

Do this instead

Each side needs its own comparison: city = 'Delhi' OR city = 'Mumbai'. Or use IN ('Delhi', 'Mumbai').

Oops

Mixing AND and OR with no brackets and trusting the result.

Do this instead

Add brackets every time both appear. Then test with a row you know should be excluded.

Your mission

Break it, then fix it

~20 min

Quick check

How does SQL group a = 1 OR b = 2 AND c = 3?

Go deeper

  1. 1Write a filter like city = 'Pune' OR city = 'Delhi' AND amount > 1000, then add parentheses and compare the results.
  2. 2Always wrap OR groups in parentheses when they sit next to AND.
  3. 3Rewrite a NOT condition in a positive form and check both return the same rows.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge