DAY 4: SQL - WHERE Clause & Filtering

Guru Charan Pathalla

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:

  1. SQL Joins Explained (20:10)
    https://www.youtube.com/watch?v=8grUQO38J6A

  2. SQL Joins Tutorial for Beginners (15:30)
    https://www.youtube.com/watch?v=2HVMiPPuPIM

  3. SQL 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:

  1. Open SQLite Browser with your Superstore dataset (from Day 2)
  2. Navigate to the "Execute SQL" tab
  3. 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:

  1. Type this query to find all East region orders:
    SELECT * FROM Orders
    WHERE Region = 'East'
    LIMIT 20;
  2. Click Execute (▢️)
  3. 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.

Tip: Press Ctrl+Enter to run

Exercise 2: WHERE with Numeric Comparisons

Step-by-Step Instructions:

  1. Find high-value orders (Sales > 1000):
    SELECT OrderID, ProductName, Sales
    FROM Orders
    WHERE Sales > 1000
    ORDER BY Sales DESC;
  2. Find small quantities (Quantity <= 2):
    SELECT ProductName, Quantity, Sales
    FROM Orders
    WHERE Quantity <= 2
    LIMIT 20;
  3. 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.

Tip: Press Ctrl+Enter to run

Exercise 3: Combining Conditions with AND

Step-by-Step Instructions:

  1. Find West region AND high-value orders:
    SELECT ProductName, Region, Sales
    FROM Orders
    WHERE Region = 'West' AND Sales > 500
    ORDER BY Sales DESC;
    Both conditions must be true!
  2. Find Technology products with discount:
    SELECT ProductName, Category, Discount, Sales
    FROM Orders
    WHERE Category = 'Technology' AND Discount > 0;
  3. 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.

Tip: Press Ctrl+Enter to run

Exercise 4: Using OR for Alternative Conditions

Step-by-Step Instructions:

  1. Find orders from East OR West:
    SELECT ProductName, Region, Sales
    FROM Orders
    WHERE Region = 'East' OR Region = 'West'
    LIMIT 30;
    Either condition can be true!
  2. Find extreme values (very high or very low sales):
    SELECT ProductName, Sales
    FROM Orders
    WHERE Sales > 5000 OR Sales < 10
    ORDER BY Sales DESC;
  3. Combining AND with OR (use parentheses!):
    SELECT ProductName, Region, Category, Sales
    FROM Orders
    WHERE (Region = 'East' OR Region = 'West')
      AND Category = 'Furniture';
    Parentheses ensure OR is evaluated first, then AND

πŸ’‘ 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.

Tip: Press Ctrl+Enter to run

Exercise 5: Advanced Filtering with IN, BETWEEN, LIKE

Step-by-Step Instructions:

  1. IN - Match multiple values (cleaner than multiple ORs):
    SELECT ProductName, Region, Sales
    FROM Orders
    WHERE Region IN ('East', 'West', 'Central')
    LIMIT 20;
    This is cleaner than: WHERE Region = 'East' OR Region = 'West' OR Region = 'Central'
  2. BETWEEN - Range of values:
    SELECT ProductName, Sales
    FROM Orders
    WHERE Sales BETWEEN 100 AND 500
    ORDER BY Sales;
    Includes both 100 and 500 (inclusive)
  3. 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
  4. 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 list
  • BETWEEN x AND y - Inclusive range
  • LIKE 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.

Tip: Press Ctrl+Enter to run

🎯 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
  1. Find orders with Profit less than 0 (losses)
  2. Select California customers
  3. Find sales between 500 and 2000
  4. Get products with names starting with β€˜Chair’
  5. Select East OR West regions with Sales>1000
  6. Find orders NOT in South region
  7. Get customers with names ending in β€˜son’
  8. Select high-value orders: Sales>5000 OR Profit>1000

Daily Assignment (60 min):

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'?

Have feedback or questions?