SQL Tutorial 0/85 lessons ~6 min read Lesson 12

    WHERE Clause

    WHERE filters rows before grouping or projection.

    Course progress0%
    Focus
    7 guided sections
    Practice signal
    Examples included
    Career prep
    Foundation builder

    Introduction

    WHERE filters rows before grouping or projection. It is your single most-used optimization tool — a good WHERE turns a 10-second scan into a 5-millisecond index lookup.

    Understanding the topic

    Core concepts to understand:

    • Comparison: = < > <= >= <>.
    • Logical: AND, OR, NOT.
    • Membership: IN, NOT IN.
    • Pattern: LIKE, ILIKE (case-insensitive in PG), ~ regex.
    • NULL: IS NULL / IS NOT NULL — never = NULL.
    • Range: BETWEEN a AND b (inclusive both sides).

    Syntax reference

    Visual workflow / architecture:

    bash
    Query rows ── WHERE filter ──▶ remaining rows ──▶ GROUP/SELECT
    WHERE status = 'paid'
    AND amount > 100
    AND created_at >= now() - interval '7 days'
    AND email ILIKE '%@gmail.com'
    Syntax Pattern
    SELECT <cols>
    FROM   <table>
    WHERE  <col> <op> <value>
       [AND|OR <col> <op> <value> ...];
    • WHEREKeeps only rows where the predicate is TRUE.
    • =, <, >Comparison operators.
    • AND / ORCombine multiple conditions.
    • IN / LIKE / BETWEENSet, pattern and range matching.
    • IS NULLRequired for NULL — never use = NULL.
    Live Example
    sql
    SELECT id, email, amount
    FROM orders
    WHERE status = 'paid'
    AND amount > 50;
    orders
    idemailstatusamount
    101leo@acme.iopaid120
    102mia@acme.iopending80
    103ana@acme.iopaid45
    104rio@acme.iopaid220
    filtered
    idemailamount
    101leo@acme.io120
    104rio@acme.io220
    WHERE filter
    drops rows that don't match

    WHERE acts like a funnel — only matching rows continue downstream.

    Real-world use

    Every page in every product is filtered: 'unread emails', 'orders this month', 'active users'. WHERE drives all of it.

    Best practices

    • Filter first, project last — use WHERE, not HAVING, for row filters.
    • Make sure WHERE columns have indexes for big tables.
    • Avoid functions on indexed columns: WHERE lower(email) = ... kills the index.

    Common mistakes

    • = NULL never matches — use IS NULL.
    • NOT IN (...) with NULLs always returns empty.
    • Functions on columns prevent index use.

    Hands-on exercise

    Interview preparation — practice these questions:

    • Q1. Why doesn't = NULL work?
    • Q2. Difference between WHERE and HAVING.
    • Q3. LIKE vs ILIKE.
    • Q4. What is a sargable predicate?
    • Q5. Inclusive nature of BETWEEN.
    Ready to mark this lesson complete?Track your journey across the entire course.