SQL · Module 02: Filtering, NULL Logic & SortingTutorial 4 of 24

2.1 Filtering Rows with WHERE, AND, OR, IN & BETWEEN

Master row-level filtering with WHERE, comparison operators, IN vs OR, BETWEEN vs half-open ranges for timestamps, sargable index-friendly filters, and the AND/OR precedence bug.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

1. How WHERE Works Visually

Think of WHERE as a strict security gate: every row loaded by FROM is tested against your condition, and only rows that evaluate to TRUE pass through to the next stage.

All 4 Rows (FROM)Aarav · ₹1200 · paidMeera · ₹300 · paidKabir · ₹1500 · cancelRiya · ₹950 · paid→WHERE GATEamount >= 500ANDstatus = 'paid'→2 Matching RowsAarav · ₹1200Riya · ₹950
WHERE evaluates every single row independently: only rows satisfying BOTH amount >= 500 AND status = 'paid' survive.

2. Complete Comparison & Range Operator Reference

OperatorMeaningExampleNotes
=Exact equalitystatus = 'paid'Case-sensitive in PostgreSQL, case-insensitive in default MySQL!
<> or !=Not equalstatus <> 'cancelled'<> is ANSI SQL standard; != works in Postgres/MySQL/SQLite
>, >=, <, <=Numeric, date, or alphabetical orderamount >= 500Works on INT, DECIMAL, DATE, TIMESTAMP, VARCHAR
IN (...)Matches any value in a setcity IN ('Bengaluru', 'Pune')Cleaner and easier for the optimizer than chained ORs
NOT IN (...)Excludes values in a setrole NOT IN ('banned', 'bot')⚠️ Watch out if the list contains NULL (Lesson 2.2!)
BETWEEN a AND bInclusive range (>= a AND <= b)price BETWEEN 100 AND 500Both 100 and 500 are included!

3. Crucial Differences That Trip Up Developers

A. IN vs Multiple OR Conditions

SQL
-- ❌ Repetitive and error-prone
SELECT order_id, city FROM orders
WHERE city = 'Bengaluru' OR city = 'Mumbai' OR city = 'Pune' OR city = 'Delhi';

-- ✅ Clean, readable, and optimizer-friendly
SELECT order_id, city FROM orders
WHERE city IN ('Bengaluru', 'Mumbai', 'Pune', 'Delhi');

B. BETWEEN vs Half-Open Ranges (>= and <) for Dates/Timestamps

PatternExampleVerdict
BETWEEN on DATEorder_date BETWEEN '2026-11-01' AND '2026-11-30'✅ Fine when column is a pure DATE (no time part)
BETWEEN on TIMESTAMPcreated_at BETWEEN '2026-11-01' AND '2026-11-30'❌ BUG! Misses all orders on Nov 30 after 00:00:00!
Half-open >= and <created_at >= '2026-11-01' AND created_at < '2026-12-01'✅ Always exact for both DATE and TIMESTAMP (even leap years!)

C. AND vs OR Operator Precedence (The Classic Bug!)

Just like * runs before + in math, NOT → AND → OR is SQL's strict order of precedence.

SQL
-- ❌ BUGGY: SQL reads this as: city = 'Delhi' OR (city = 'Mumbai' AND status = 'paid')
-- Returns unpaid Delhi orders by mistake!
SELECT order_id, city, status
FROM orders
WHERE city = 'Delhi' OR city = 'Mumbai' AND status = 'paid';

-- ✅ FIXED: Always wrap OR groups in parentheses!
SELECT order_id, city, status
FROM orders
WHERE (city = 'Delhi' OR city = 'Mumbai')
  AND status = 'paid';

D. Index-Friendly ("Sargable") vs Index-Breaking WHERE Clauses

Never wrap an indexed column inside a function in WHERE — it forces the database to ignore your index and scan every single row!

SQL
-- ❌ SLOW: Wrapping created_at in YEAR() disables B+ Tree index lookup!
SELECT * FROM orders
WHERE EXTRACT(YEAR FROM created_at) = 2026;

-- ✅ FAST (Sargable): Leaves created_at bare so the B+ Tree index jumps right to 2026!
SELECT * FROM orders
WHERE created_at >= '2026-01-01'
  AND created_at <  '2027-01-01';

4. Watch Compound WHERE Filtering Execute Step-by-Step

Tracing WHERE + IN + BETWEEN
Interactive SQL Execution Tracer · Step 1 of 4 (1. FROM orders)
1SELECT order_id, customer, amount
2→FROM orders
3WHERE city IN ('Bengaluru', 'Pune')
4 AND amount BETWEEN 500 AND 1500;
Live Table State · 1. FROM orders4 rows
order_idcustomercityamount
501AaravBengaluru1200
502MeeraDelhi900
503KabirPune350
504RiyaPune850
What the DB engine just did: The database begins with all 4 rows in orders.

5. Practice Challenge

Write a query to find all orders placed in November 2026 (using a TIMESTAMP column created_at) that are either 'paid' or 'shipped' and have amount >= 1000.


6. Quick Check Your Understanding

Module 2.1 Quick Quiz

Q1.Why is created_at BETWEEN '2026-11-01' AND '2026-11-30' dangerous on a TIMESTAMP column?
Q2.Why is WHERE EXTRACT(YEAR FROM created_at) = 2026 slower than WHERE created_at >= '2026-01-01' AND created_at < '2027-01-01'?

Keep Exploring: Related Lessons & Tools

All Courses →