Filtering Data with the WHERE Clause 🎯
In a database containing 50 million records, you rarely want to retrieve all 50 million rows. You want specific subsets:
- "Show all active accounts in Maharashtra."
- "Find orders placed between October 1st and October 15th exceeding ₹5,000."
- "List customers whose last name starts with 'S'."
In SQL, row filtering is performed using the WHERE clause.
SELECT column1, column2FROM table_nameWHERE condition;The database evaluates the WHERE condition on every row. Only rows that evaluate to TRUE are included in your result.
1. Comparison Operators ⚖️
SQL provides familiar comparison operators:
| Operator | Meaning | Example |
|---|---|---|
= | Equal to | WHERE department = 'Engineering' |
<> or != | Not equal to | WHERE department <> 'Sales' |
> | Greater than | WHERE salary > 70000 |
< | Less than | WHERE salary < 60000 |
>= | Greater than or equal to | WHERE salary >= 64000 |
<= | Less than or equal to | WHERE salary <= 55000 |
Important SQL Convention: String and Date literals must always be enclosed in single quotes (
'Marketing','2024-01-15'). Double quotes are reserved for column/table identifiers.
2. Combining Conditions: AND, OR, NOT 🔀
The AND Operator (All conditions must be TRUE)
Find engineers whose salary exceeds ₹90,000:
SELECT first_name, salary, departmentFROM employeesWHERE department = 'Engineering' AND salary > 90000;The OR Operator (At least one condition must be TRUE)
Find employees in either Marketing or Sales:
SELECT first_name, departmentFROM employeesWHERE department = 'Marketing' OR department = 'Sales';The NOT Operator (Inverts the condition)
Find employees outside the Engineering department:
SELECT first_name, departmentFROM employeesWHERE NOT (department = 'Engineering');⚠️ Operator Precedence Warning: Always Use Parentheses!
In SQL, AND has higher precedence than OR (just like multiplication takes precedence over addition).
Look at this ambiguous query:
-- ⚠️ BUGGY QUERY: Does not do what you think!SELECT first_name, department, salaryFROM employeesWHERE department = 'Marketing' OR department = 'Sales' AND salary > 60000;Because AND binds first, this query is evaluated as:
WHERE department = 'Marketing' OR (department = 'Sales' AND salary > 60000).
Every single person in Marketing will be returned, regardless of their salary!
The Fix: Always use explicit parentheses:
-- ✅ CLEAN & PREDICTABLE:SELECT first_name, department, salaryFROM employeesWHERE (department = 'Marketing' OR department = 'Sales') AND salary > 60000;3. The IN Operator: Cleaner Multi-Value Matching 📋
Instead of chaining multiple OR conditions:
-- Clunky:WHERE country = 'India' OR country = 'Germany' OR country = 'Japan'Use the clean, readable IN operator:
-- Elegant:SELECT first_name, departmentFROM employeesWHERE department IN ('Marketing', 'Sales', 'HR');You can also use NOT IN to exclude specific sets:
WHERE department NOT IN ('Engineering', 'Executive');4. The BETWEEN Operator: Inclusive Ranges ↔️
To filter values within a continuous range (numbers or dates), use BETWEEN ... AND ...:
SELECT first_name, salaryFROM employeesWHERE salary BETWEEN 60000 AND 95000;Crucial Rule: In SQL,
BETWEENis inclusive on both boundaries!WHERE salary BETWEEN 60000 AND 95000is mathematically equivalent to:WHERE salary >= 60000 AND salary <= 95000.
5. Pattern Matching with LIKE & Wildcards 🔍
When searching for text fragments (e.g., finding all emails ending with @gmail.com), use LIKE with wildcard symbols:
| Wildcard | Meaning | Example | Matches |
|---|---|---|---|
% | Matches zero, one, or multiple characters | 'M%' | "Aarav", "Mike", "M" |
_ | Matches exactly one character | '_at' | "Cat", "Hat", "Bat" (not "Chat") |
Common Pattern Examples:
-- Starts with 'Ma'SELECT * FROM employees WHERE first_name LIKE 'Ma%';-- Ends with 'pre'SELECT * FROM employees WHERE last_name LIKE '%pre';-- Contains 'ar' anywhere insideSELECT * FROM employees WHERE first_name LIKE '%ar%';-- Exactly 4 letters longSELECT * FROM employees WHERE first_name LIKE '____';Case-Sensitivity Note: In standard SQL and PostgreSQL,
LIKEis case-sensitive ('aarav%'won't match'Aarav'). In PostgreSQL, useILIKEfor case-insensitive matching.
6. The Three-Valued Logic Trap: Handling NULL 🕳️
In SQL, NULL does NOT mean zero 0 or an empty string "".NULL represents the total absence of data (Unknown).
Because NULL is unknown, mathematical comparisons like = NULL or != NULLnever evaluate to TRUE. They evaluate to UNKNOWN!
-- ❌ BUG: WILL RETURN 0 ROWS EVERY TIME!SELECT * FROM employees WHERE bonus = NULL;To check for missing data, you must use IS NULL or IS NOT NULL:
-- ✅ CORRECT:SELECT first_name, salary, bonusFROM employeesWHERE bonus IS NULL;-- Find employees who DO have a bonus recorded:SELECT first_name, salary, bonusFROM employeesWHERE bonus IS NOT NULL;Flashcard Checkpoint 🎴
Why does 'WHERE column = NULL' fail to return rows with missing values?
Is the BETWEEN operator in SQL inclusive or exclusive of its boundary values?