DAY 4: SQL - WHERE Clause & Filtering
Learning Objectives: - Master WHERE clause for filtering data - Use comparison operators (=, <, >, <=, >=, <>) - Learn logical operators (AND, OR, NOT) - Use IN, BETWEEN, LIKE for advanced filtering
Topics Covered (60 min):
1. WHERE Clause Basics - Syntax:
SELECT * FROM table WHERE condition; - Numeric:
WHERE Sales > 1000 - Text:
WHERE Region = 'East' (use single quotes) - NULL:
WHERE column IS NULL or IS NOT NULL
2. Comparison Operators - = (equal),
<> or != (not equal) - >
(greater than), < (less than) - >=
(greater or equal), <= (less or equal)
3. Logical Operators (Mirror Excel Day 3) - AND:
WHERE Region='East' AND Sales>1000 - OR:
WHERE Region='East' OR Region='West' - NOT:
WHERE NOT Region='South' - Combined:
WHERE (Region='East' OR Region='West') AND Sales>500
4. Advanced Filtering - IN:
WHERE Region IN ('East', 'West', 'Central') - BETWEEN:
WHERE Sales BETWEEN 100 AND 1000 - LIKE:
WHERE CustomerName LIKE 'A%' (starts with A) - Wildcards:
% = any characters, _ = single character
Video Resources:
SQL Joins Explained (20:10)
https://www.youtube.com/watch?v=8grUQO38J6ASQL Joins Tutorial for Beginners (15:30)
https://www.youtube.com/watch?v=2HVMiPPuPIMSQL Joins Made EASY! Learn with Animations (15:00)
https://www.youtube.com/watch?v=GXSnaR1Xx5c
AI Learning Prompts (Concept Understanding Only):
Understanding WHERE Clause (Mirror Excel Day 3):
I learned Excel filtering yesterday. Help me understand SQL WHERE:
1. How does SQL WHERE clause compare to Excel AutoFilter?
2. What is the basic syntax of WHERE?
3. Show me all comparison operators: =, <, >, <=, >=, <> (or !=)
4. How do I filter text vs numbers vs dates?
5. Provide examples using a Movies table (Title, Genre, Year, Rating, Director)
6. What happens with NULL values in WHERE clause?
Explain with examples using movie or book data (not sales).
Understanding Logical Operators:
Explain AND, OR, NOT in SQL:
1. How do I combine multiple conditions with AND?
2. How does OR work differently from AND?
3. What does NOT do?
4. Can I mix AND and OR? How do I use parentheses?
5. Show me examples using a Cars table (Make, Model, Year, Price, Color)
6. What's the order of precedence (AND vs OR)?
Provide clear examples with vehicle or product data.
Understanding Pattern Matching with LIKE:
Explain SQL pattern matching:
1. What is the LIKE operator used for?
2. How do wildcards work: % (multiple chars) and _ (single char)?
3. Show me examples: starts with, ends with, contains
4. How do I find names starting with 'A'?
5. What about case sensitivity?
6. Give examples using a Cities table (CityName, Country, Population)
Use geography or people names for examples.
Understanding IN and BETWEEN:
Explain IN and BETWEEN operators:
1. When should I use IN instead of multiple OR conditions?
2. What's the syntax for IN with a list of values?
3. How does BETWEEN work with numbers and dates?
4. Is BETWEEN inclusive or exclusive?
5. Show examples using a Weather table (Date, City, Temperature, Condition)
Provide examples with weather or calendar data.
Guided Practice (60 min):
π How to approach Guided Practice:
- Follow step-by-step: Work through each exercise in order
- Use provided resources: Reference the video tutorials and AI prompts if you get stuck
- Verify your work: Check your results match expected outcomes
- Take notes: Document key learnings and shortcuts you discover
- Ask for help: Use AI assistants to clarify concepts you don't understand
Using Superstore Sales dataset - SQL Practice
π Setup Instructions:
- Open SQLite Browser with your Superstore dataset (from Day 2)
- Navigate to the "Execute SQL" tab
- Today you'll learn to filter data - this is like Excel's AutoFilter but with code!
π‘ WHERE Clause = SQL's Filtering Power: While Day 3 (Excel) used AutoFilter clicking, SQL uses WHERE to write filter rules in code!
Exercise 1: Simple WHERE with Text Comparison
Step-by-Step Instructions:
- Type this query to find all East region orders:
SELECT * FROM Orders WHERE Region = 'East' LIMIT 20; - Click Execute (βΆοΈ)
- You should see only East region orders
β οΈ Important SQL Rules:
- Text values must use single quotes:
'East'not"East" - SQL is case-sensitive for values:
'East'β'east' - WHERE comes AFTER FROM, BEFORE ORDER BY
Try these variations:
SELECT ProductName, Sales, Region FROM Orders
WHERE Region = 'West'
LIMIT 15;
SELECT * FROM Orders
WHERE Category = 'Technology';
β Expected Result: Only rows matching your WHERE condition
Try It Yourself - Simple WHERE Filtering
Practice filtering with WHERE. Try modifying the query to filter by different regions or categories.
Exercise 2: WHERE with Numeric Comparisons
Step-by-Step Instructions:
- Find high-value orders (Sales > 1000):
SELECT OrderID, ProductName, Sales FROM Orders WHERE Sales > 1000 ORDER BY Sales DESC; - Find small quantities (Quantity <= 2):
SELECT ProductName, Quantity, Sales FROM Orders WHERE Quantity <= 2 LIMIT 20; - Find discounted orders (Discount > 0):
SELECT ProductName, Discount, Sales FROM Orders WHERE Discount > 0;
π’ Comparison Operators in SQL:
=Equal to>Greater than<Less than>=Greater than or equal to<=Less than or equal to<>or!=Not equal to
β Expected Result: Only rows where the numeric condition is TRUE
Try It Yourself - Numeric Comparisons
Practice using comparison operators (>, <, >=, <=). Try finding different sales ranges or quantity thresholds.
Exercise 3: Combining Conditions with AND
Step-by-Step Instructions:
- Find West region AND high-value orders:
Both conditions must be true!SELECT ProductName, Region, Sales FROM Orders WHERE Region = 'West' AND Sales > 500 ORDER BY Sales DESC; - Find Technology products with discount:
SELECT ProductName, Category, Discount, Sales FROM Orders WHERE Category = 'Technology' AND Discount > 0; - Three conditions - profitable high-quantity orders:
SELECT ProductName, Quantity, Sales, Profit FROM Orders WHERE Quantity > 5 AND Sales > 100 AND Profit > 0 LIMIT 20;
π‘ AND Logic:
- ALL conditions must be TRUE for row to appear
- Narrows your results (fewer rows)
- Like applying multiple Excel filters at once
β Expected Result: Only rows matching ALL conditions
Try It Yourself - Combining Conditions with AND
Practice combining multiple conditions. Try changing regions, sales thresholds, or adding more conditions.
Exercise 4: Using OR for Alternative Conditions
Step-by-Step Instructions:
- Find orders from East OR West:
Either condition can be true!SELECT ProductName, Region, Sales FROM Orders WHERE Region = 'East' OR Region = 'West' LIMIT 30; - Find extreme values (very high or very low sales):
SELECT ProductName, Sales FROM Orders WHERE Sales > 5000 OR Sales < 10 ORDER BY Sales DESC; - Combining AND with OR (use parentheses!):
Parentheses ensure OR is evaluated first, then ANDSELECT ProductName, Region, Category, Sales FROM Orders WHERE (Region = 'East' OR Region = 'West') AND Category = 'Furniture';
π‘ OR Logic:
- AT LEAST ONE condition must be TRUE
- Broadens your results (more rows)
- Use parentheses to control evaluation order
β Expected Result: Rows matching ANY of the OR conditions (and all AND conditions if combined)
Try It Yourself - Using OR for Alternative Conditions
Practice using OR and combining with AND. Try different regions or sales ranges with parentheses.
Exercise 5: Advanced Filtering with IN, BETWEEN, LIKE
Step-by-Step Instructions:
- IN - Match multiple values (cleaner than multiple ORs):
This is cleaner than:SELECT ProductName, Region, Sales FROM Orders WHERE Region IN ('East', 'West', 'Central') LIMIT 20;WHERE Region = 'East' OR Region = 'West' OR Region = 'Central' - BETWEEN - Range of values:
Includes both 100 and 500 (inclusive)SELECT ProductName, Sales FROM Orders WHERE Sales BETWEEN 100 AND 500 ORDER BY Sales; - LIKE - Pattern matching with wildcards:
SELECT ProductName, Sales FROM Orders WHERE ProductName LIKE '%Chair%' LIMIT 20;%= any characters. This finds products with "Chair" anywhere in the name - More LIKE examples:
-- Products starting with 'Table' SELECT ProductName FROM Orders WHERE ProductName LIKE 'Table%'; -- Products ending with 'Kit' SELECT ProductName FROM Orders WHERE ProductName LIKE '%Kit'; -- CustomerName containing 'Smith' SELECT DISTINCT CustomerName FROM Orders WHERE CustomerName LIKE '%Smith%';
π‘ Special Operators:
IN (value1, value2, ...)- Matches any value in the listBETWEEN x AND y- Inclusive rangeLIKE pattern- Pattern matching (%= any chars,_= single char)IS NULL/IS NOT NULL- Check for missing values
β Expected Result: Rows matching the specified patterns or ranges
Try It Yourself - Advanced Filtering (IN, BETWEEN, LIKE)
Practice using IN, BETWEEN, and LIKE. Try different value lists, ranges, or search patterns.
π― Practice Goal Checkpoint:
By completing these 5 exercises, you should now be able to:
- Use WHERE clause to filter data by specific conditions
- Apply comparison operators (=, >, <, >=, <=, <>)
- Combine multiple conditions with AND/OR
- Use IN for matching multiple values
- Use BETWEEN for range filtering
- Use LIKE for pattern matching with wildcards
- Understand the parallel between WHERE and Excel's AutoFilter
Key Insight: WHERE in SQL = Programmatic filtering. Instead of clicking filter dropdowns (Excel Day 3), you write logical conditions in code!
Take a 5-minute break, then move on to Independent Practice!
Independent Practice (60 min):
π‘ Hints for Independent Practice:
- Start simple: Begin with basic variations before attempting complex modifications
- Break it down: Divide complex problems into smaller, manageable steps
- Test incrementally: Verify each step works before moving to the next
- Use documentation: Refer to official docs or tutorials when needed
- Experiment: Try different approaches to find what works best
- Find orders with Profit less than 0 (losses)
- Select California customers
- Find sales between 500 and 2000
- Get products with names starting with βChairβ
- Select East OR West regions with Sales>1000
- Find orders NOT in South region
- Get customers with names ending in βsonβ
- Select high-value orders: Sales>5000 OR Profit>1000
Daily Assignment (60 min):
- Replicate ALL Excel Day 3 filtering using SQL WHERE
- Create queries for each customer segment from Day 3
- Compare results with Excel filtering
- Save as: Day04_SQL_Practice.sql
Expected Outcomes:
β Filter data effectively using WHERE clause
β Combine multiple conditions with logical operators
β Use pattern matching with LIKE
β Submit: Day04_SQL_Practice.sql
π Day 4 Quick Quiz - Test Your Knowledge!
Q1. What does the WHERE clause do in SQL?
Q2. Which operator checks if a value is NULL?
Q3. What does the LIKE operator do?
Q4. In SQL, what does % represent when used with LIKE?
Q5. Which WHERE clause finds all names starting with 'A'?