SQL · Module 4 · Lesson 31 min read

AND, OR, NOT & Precedence

Logical operators

  • AND – both conditions must be true
  • OR – at least one must be true
  • NOT – reverses a condition

⚠️ Precedence: AND before OR

Like × before + in maths: NOT first, then AND, then OR.

ini
WHERE city = 'Pokhara' OR city = 'Kathmandu' AND monthly_budget > 30000

is read as

ini
WHERE city = 'Pokhara' OR (city = 'Kathmandu' AND monthly_budget > 30000)

Always use parentheses when mixing AND and OR — it makes your intent explicit.

Truth table with NULL (three-valued logic)

ABA AND BA OR B
trueNULLNULLtrue
falseNULLfalseNULL
NULLNULLNULLNULL
  • NOT NULL (the logical NOT of unknown) is still unknown
  • So WHERE NOT (city = 'Pokhara') does not return rows where city is NULL!

Tips

  • Many ORs on one column → use IN (…) (next lesson)
  • Ranges → BETWEEN
  • Write complex filters across several lines with indentation
  • NOT can be written as NOT (…), or with specific operators: <>, NOT IN, NOT LIKE, IS NOT NULL

Example

SQL
-- AND: both must be true
SELECT title, amount FROM expenses
WHERE user_id = 1 AND amount > 2000;

-- OR: either is enough
SELECT name, city FROM users
WHERE city = 'Pokhara' OR city = 'Lalitpur';

-- ⚠️ Precedence trap
SELECT name, city, monthly_budget FROM users
WHERE city = 'Pokhara' OR city = 'Kathmandu' AND monthly_budget > 30000;
-- Ravi (Pokhara), Sita (Kathmandu, 40000), Maya (Pokhara) — AND was applied first

-- ✅ Parentheses make the meaning clear
SELECT name, city, monthly_budget FROM users
WHERE (city = 'Pokhara' OR city = 'Kathmandu')
  AND monthly_budget > 30000;
-- Sita only

-- NOT
SELECT title FROM bills WHERE NOT paid;

-- NULL surprise: Hari (city NULL) is NOT returned here
SELECT name FROM users WHERE NOT (city = 'Pokhara');
-- Asha, Sita, Bikash — Hari is missing!

-- ✅ Include unknown cities explicitly
SELECT name FROM users WHERE city <> 'Pokhara' OR city IS NULL;
-- Asha, Sita, Bikash, Hari