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/SELECTWHERE status = 'paid'AND amount > 100AND 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, amountFROM ordersWHERE status = 'paid'AND amount > 50;
orders
| id | status | amount | |
|---|---|---|---|
| 101 | leo@acme.io | paid | 120 |
| 102 | mia@acme.io | pending | 80 |
| 103 | ana@acme.io | paid | 45 |
| 104 | rio@acme.io | paid | 220 |
runs
filtered
| id | amount | |
|---|---|---|
| 101 | leo@acme.io | 120 |
| 104 | rio@acme.io | 220 |
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
= NULLnever 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
= NULLwork? - 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.