Learn/SQL/Querying Data

WHERE — Filtering Rows

WHERE keeps only rows that match a condition. Without it, SELECT returns every row in the table.

Beginner~14 min read

Filter Flow

Rows filtered by WHERE

Sample Data

usersjson
1| user_id | email | is_active |
2|---------|---------------------|-----------|
3| 1 | [email protected] | true |
4| 2 | [email protected] | false |
5| 3 | [email protected] | true |
ordersjson
1| order_id | customer_id | status | total_amount |
2|----------|-------------|----------|--------------|
3| 1001 | 1 | paid | 49.99 |
4| 1002 | 1 | shipped | 12.50 |
5| 1003 | 3 | pending | 8.00 |

Comparison Operators

Active users onlyjson
1SELECT email
2FROM users
3WHERE is_active = TRUE;
Expected outputjson
1| email |
2|---|
Orders over $20json
1SELECT order_id, total_amount
2FROM orders
3WHERE total_amount > 20;
Expected outputjson
1| order_id | total_amount |
2|---|---|
3| 1001 | 49.99 |

AND / OR

ExpressionTrue when
A AND BBoth A and B are true
A OR BEither A or B is true
NOT AA is false
Paid or shipped orders over $10json
1SELECT order_id, status, total_amount
2FROM orders
3WHERE total_amount > 10
4 AND (status = 'paid' OR status = 'shipped');

IN, BETWEEN, LIKE

IN — match any value in a listjson
1SELECT email FROM users
2WHERE user_id IN (1, 3);
BETWEEN — inclusive rangejson
1SELECT order_id, total_amount FROM orders
2WHERE total_amount BETWEEN 8 AND 15;
LIKE — pattern matchjson
1SELECT email FROM users
2WHERE email LIKE '%@example.com';

IS NULL

Never use = NULL

WHERE phone = NULL is always unknown. Use IS NULL or IS NOT NULL.
Correct NULL checkjson
1SELECT email FROM users WHERE phone IS NULL;

Common Mistakes

  • Using = NULL instead of IS NULL.
  • OR without parentheses changing logic unintentionally.
  • Leading wildcard LIKE '%text' — often cannot use indexes efficiently.

Practice Prompts

  1. Find orders with status pending.
  2. Find users whose email contains alice.
  3. Find orders with total between 10 and 50 inclusive.

Frequently Asked Questions

Where does WHERE run in a query?
Logically, WHERE filters rows before SELECT projects columns and before ORDER BY sorts. Only matching rows continue.
Why does WHERE status = NULL fail?
NULL is unknown, not equal to anything. Use IS NULL or IS NOT NULL instead.
What is the difference between LIKE and =?
= matches exact values. LIKE matches patterns with % (any length) and _ (one character) wildcards.
Do I need parentheses with AND and OR?
Use parentheses when mixing AND/OR to make intent explicit: WHERE (a OR b) AND c.
Can WHERE filter on multiple tables?
Not directly — use JOIN first, then filter on joined columns, or use a subquery (covered later).