SQL Filtering (WHERE) π
Mentor's Note: A database can have millions of rows.
WHEREis your "Magnifying Glass"βit helps you ignore the noise and find exactly the row you are looking for. π‘
π The Scenario: The Police Investigation πβ
Imagine you are a detective searching for a specific car in a massive parking lot.
- The Problem: There are 10,000 cars. You can't check them all. π¦
- The Filter: You only want to see cars WHERE the color is 'Red' π΄ and the brand is 'Toyota' π.
- The Result: Instead of 10,000 cars, you now have only 5 to check. This is exactly what the
WHEREclause does in SQL. β
π Concept Explanationβ
1. The WHERE Clauseβ
The WHERE clause is used to extract only those records that fulfill a specified condition.
2. Common Comparison Operatorsβ
| Operator | Meaning |
|---|---|
= | Equal to |
<> or != | Not equal |
> | Greater than |
LIKE | Search for a pattern (e.g. V%) π |
BETWEEN | Within a range |
IN | Match any value in a list |
π¨ Visual Logic: The Filter Funnelβ
π» Implementations (Dialect Comparison)β
- Oracle SQL
- MySQL
- PostgreSQL
-- π Action: Find employees in IT with high pay
SELECT name, salary
FROM employees
WHERE salary > 50000
AND department = 'IT';
-- π Action: Same as Oracle
SELECT name, salary
FROM employees
WHERE salary > 50000
AND department = 'IT';
-- π Action: Same as Oracle
SELECT name, salary
FROM employees
WHERE salary > 50000
AND department = 'IT';
π Sample Dry Runβ
Goal: Find students with marks > 80
| Name | Marks | Condition (> 80) | Action |
|---|---|---|---|
| Vishnu | 95 | β True | Keep |
| Ankit | 75 | β False | Discard |
π Technical Analysisβ
- Text Comparison: In Oracle, string comparison is case-sensitive ('IT' != 'it'). In MySQL, it depends on the database collation (often case-insensitive).
- WILDCARDS:
%= Zero or more characters._= Exactly one character.
π― Practice Lab π§ͺβ
Task: Find all names in the USERS table that end with the letter 'a'.
Hint: Use LIKE '%a'. π‘
π‘ Interview Tip πβ
"Interviewers love asking: 'How do you check for empty values?' Answer: Use
IS NULLorIS NOT NULL. NEVER use= NULLbecause NULL is not a value, it is an absence of data!"
π‘ Pro Tip: "A program is like a poem: you build it from small parts, and it becomes a masterpiece." - Anonymous