Filtering: Beginner
Cloudflare processes over 50 billion DNS queries and blocks more than 155 billion threats every day, and the reason malicious traffic is stopped before it can reach millions of websites is that Cloudflare applies logical filtering conditions to each request the moment it arrives. Their WAF rules evaluate conditions like source IP, URL patterns, and request headers to decide in milliseconds whether a request should pass or be blocked, protecting over 20 percent of all web traffic globally. Every filter you are about to learn, from WHERE and AND to comparison operators, is the same kind of conditional logic Cloudflare engineers express in their firewall rule engine.
WHERE clause for filtering rows
Narrow results to only matching rows
WHERE narrows your result set to only the rows that match a condition. Without it, every query returns the entire table. When a table holds millions of rows, the difference between a full scan and a targeted filter determines whether a query is useful at all.
Rachel Voss ran a company-wide employee report. Five of her eight people never showed up. Nobody's been terminated, and nobody can explain the gap. She was one signature away from filing an incident report with the board.
Eight employees. Four departments. One report with three rows.
| id | name | department | salary |
|---|---|---|---|
| 1 | Chen | Engineering | 85000 |
| 2 | Patel | Engineering | 92000 |
| 3 | Osei | Marketing | 68000 |
| 4 | Ruiz | Sales | 74000 |
| 5 | Kim | Engineering | 78000 |
| 6 | Tanaka | Marketing | 71000 |
| 7 | Adams | Sales | 82000 |
| 8 | Silva | HR | 76000 |
| device_id | status |
|---|---|
| device_001 | active |
| device_002 | inactive |
| device_003 | active |
| device_004 | pending |
| device_005 | active |
| device_id | status |
|---|
The WHERE keyword is your entry point to filtering. It tells SQL exactly which rows you want to keep based on conditions you define.
WHERE is the word you use to start filtering. It comes after FROM and tells SQL what condition to check.
Everything after WHERE is your filter condition. The condition is a test that can be true or false for each row.
Example
Problem: Find all students with a grade of A.
Solution: Use WHERE with the = operator to keep only rows where grade is exactly "A."
Remember
WHEREalways comes afterFROM- You can combine multiple conditions with
AND - If you skip
WHERE, you get every row in the table
The Equals Operator
Basic Syntax
The equals sign (=) checks for exact matches. It is the most common filter you will use.
When you write status = 'active', SQL keeps only rows where status is exactly "active". Everything else gets filtered out.
Example
Problem: Show only active devices.
Solution: Filter for status = 'active'. Devices with "inactive", "pending", or any other status are excluded.
Use = when you know exactly what you are looking for:
Practice using WHERE and the equals operator to filter products by category.
> Fill in the missing parts to show only electronics products with their names and prices.
SELECT name, price FROM products category 'electronics'
The WHERE clause is the foundation of almost every analytical query. Without it, you retrieve the entire table, which is rarely what you need.
Exact matching with the = operator is the most efficient type of filter because the database can use indexes to locate matching rows directly.
As your queries grow more complex, you will combine WHERE with multiple conditions, but the single-condition WHERE clause you practiced here remains the building block for all of them.
Equals and not equals (=, !=)
Match or exclude rows by exact values
The != operator means "not equal to". It is the opposite of =. Use it to exclude one specific value.
When you write status != 'inactive', you keep everything EXCEPT rows where status is "inactive". Watch how the filter evaluates each row against this condition.
| device_id | status |
|---|---|
| device_001 | active |
| device_002 | inactive |
| device_003 | active |
| device_004 | inactive |
| device_005 | pending |
| device_id | status |
|---|
Rows with "inactive" are filtered out (device_002 and device_004). Active and pending rows pass through because those values are not equal to "inactive."
Example
Problem: Show all devices except inactive ones.
Solution: Use != to exclude "inactive". You get active, pending, and maintenance devices.
Equals and Not Equals
Side-by-Side Comparison
By filtering out trial accounts with !=, we get a clean list of users who have converted to paid plans.
Alternative Syntax: <>
Both != and <> mean exactly the same thing. Think of <> as a visual representation of "not equal" -- the angle brackets point away from each other, suggesting inequality.
Most programmers prefer != because it is more common in other programming languages, but <> is the traditional SQL standard. Use whichever feels more natural to you.
- Keeps matching rows
- Find a specific value
- Most common filter
- Removes matching rows
- Exclude a specific value
- Also written as <>
> Complete this query to show all orders that are not from trial accounts.
SELECT order_id, account_type FROM orders WHERE account_type
The <> operator is the SQL standard for not-equals. Use it whenever you need to exclude a single specific value from your results.
Not equals filters are most effective when you want to exclude a single known bad value from a dataset, such as removing test accounts or internal records before analysis.
Comparison operators (<, >)
Find rows above or below a threshold
Example: Greater Than
Problem: Find big spenders who spent more than $500.
Solution: Use > 500. Users who spent exactly $500 are NOT included. Only amounts above 500 pass the filter.
Working with Ranges
Inclusive vs Exclusive
| product_id | stock |
|---|---|
| P001 | 5 |
| P002 | 15 |
| P003 | 10 |
| P004 | 3 |
| P005 | 8 |
| product_id | stock |
|---|
Problem: Find products low on stock (10 or fewer items).
With <=: Products with exactly 10 items ARE included.
With <: Products with exactly 10 items would be EXCLUDED.
Example: Less Than or Equal
Problem: Find orders of $200 or less.
Solution: Use <= to include the boundary value. Orders at exactly $200 are included because the operator is "less than or equal to."
- Compares each row to your number or date
- The boundary value (the exact number) is included with
>=and<=, excluded with>and< - You can combine comparisons to create ranges (covered in the next section)
> Complete this query to find products priced above $50.
SELECT product_id, FROM products WHERE price 50
In the next section, you will learn to combine comparison operators to create powerful range filters for date-based reporting and numeric threshold analysis.
IN and NOT IN for list matching
Match rows against a list of values
IN checks if a value matches anything in a list. Instead of writing multiple = checks with OR, you can list all acceptable values in one place.
Pattern for IN operator:
Example
Problem: Show only books, tools, and toys.
Solution: List all three types in IN. Notice that "food" is excluded because it is not in the list.
Watch how IN checks each row against the list of allowed values.
| id | type |
|---|---|
| A1 | book |
| B2 | tool |
| C3 | food |
| D4 | toy |
| E5 | book |
| id | type |
|---|
Why IN Is Powerful
Without IN, you would need to write a separate = check for each value. IN replaces all of those with a single, clean expression.
This single IN expression checks against three values at once. Adding more values just means extending the list.
More Examples
The IN operator simplifies checking if a value matches any item in a list.
Excluding with NOT IN
Just as IN finds rows matching a list, NOT IN excludes rows matching a list. This is invaluable for filtering out unwanted categories.
Basic Syntax
The NOT IN operator is the inverse of IN. It returns rows where a value does not match any item in a specified list. This is useful when you need to exclude multiple specific values at once.
While you could chain multiple != conditions together, NOT IN provides a much cleaner and more maintainable syntax when excluding several values.
Basic Example
Real-World Example
NOT IN is especially valuable in analytics and reporting when you need to exclude test data, invalid records, or specific categories:
- More efficient than writing separate
!=checks for each value - Optimized similarly to
INfor quick membership testing - Useful for maintaining exclusion lists that may change over time
Compare IN and NOT IN on the same data:
Knowing when to use IN versus NOT IN simplifies multi-value filtering.
> Complete this query to find orders with a status of Shipped, Delivered, or Returned.
SELECT order_id, FROM orders WHERE status ( 'Shipped', 'Delivered', 'Returned' )
IN is equivalent to chaining multiple OR conditions but produces cleaner, more maintainable SQL.
NOT IN excludes rows matching any value in the list, useful for filtering out unwanted categories or statuses.
Be cautious with NOT IN when the list might contain NULL values, as this can cause unexpected empty results.
AND for combining conditions
Combine multiple filters in one query
Real-world queries often need multiple criteria. The AND operator lets you layer conditions to narrow results precisely.
AND lets you combine multiple conditions. A row must pass ALL conditions to be included. If any condition fails, the row is excluded.
Think of AND as stacking filters on top of each other. Each filter narrows down the results further.
Example
Problem: Find active US users who logged in recently.
Solution: Use AND to require all three conditions. Users must be from US AND be active AND have logged in after January 1st.
How AND Works
Practical Applications
AND shines when you need to create precise segments from your data by combining multiple requirements.
AND is essential whenever you need to narrow results with multiple criteria.
Putting It All Together
Most real queries combine several operators. Here is an example using =, >, and IN all at once:
Problem: Find large completed orders from North America.
Solution: Combine three filters. Orders must be completed AND over $100 AND from either US or Canada.
- Use specific comparison operators for the task at hand
- Use IN for multiple exact matches instead of chaining OR
- Combine AND conditions to narrow results precisely
- Test filters on small datasets before running on large tables
- Use single quotes around string values in comparisons
- Don't use = to compare with NULL (use IS NULL instead)
- Don't forget that string comparisons are case-sensitive
- Don't mix up = (equality) with := (assignment in some databases)
- Don't use != and <> interchangeably without checking your database
> You are a logistics analyst at DoorDash investigating delivery delays across fulfilment hubs and need to isolate the exact shipments responsible. You query the shipments table to filter down from millions of daily records to only the delayed orders matching specific criteria.
WHERE narrows the entire shipments table to only the rows that meet your delay criteria, excluding irrelevant completed deliveries.= operator finds shipments with an exact status match like status = 'delayed' to pinpoint the affected records.IN matches shipments belonging to any of several hub region codes at once, replacing a chain of OR conditions with a cleaner list.AND stacks the status, region, and date conditions together so only shipments satisfying every criterion appear in the final result.WHERE is the keyword that starts filtering and comes after FROM in a query= operator finds exact matches; use it when you know precisely what value you need!= operator (or <>) excludes a specific value from results>, <, >=, <=) filter by ranges and work with numbers and datesIN checks if a value matches any item in a list; cleaner than multiple OR conditionsNOT IN excludes rows that match any value in a listAND combines conditions so all must be true for a row to be includedFiltering: Beginner
WHERE: your database bouncer
- Category
- SQL
- Difficulty
- beginner
- Duration
- 35 minutes
- Challenges
- 0 hands-on challenges
Topics covered: WHERE clause for filtering rows, Equals and not equals (=, !=), Comparison operators (<, >), IN and NOT IN for list matching, AND for combining conditions
Lesson Sections
- WHERE clause for filtering rows (concepts: sqlWhere)
SQL checks each row one by one. For every row, it asks: does this row meet my condition? If yes, keep it. If no, skip it. The SQL code tells the database to scan the status column for each device. When status equals "active", that row passes through to the results. All other rows are filtered out. Basic pattern: Example Here is a simple example filtering students by grade. Remember Filters are built with simple comparison operators: Which query correctly filters for active users? The Equals Oper
- Equals and not equals (=, !=)
Sometimes you need to find everything except a specific value. The not equals operator is the inverse of exact matching. Example Equals and Not Equals Understanding when to use each operator is essential. One finds matches while the other excludes them. Side-by-Side Comparison This same pattern works for any exclusion filter. Here we exclude trial accounts to show only paying customers. Alternative Syntax: <> In SQL, you can write "not equal to" in two ways. Both produce identical results: Under
- Comparison operators (<, >)
Numeric and date comparisons let you filter based on relative values rather than exact matches. These operators compare values to find things that are bigger, smaller, or within a range. They work with numbers and dates. Comparison operators: Example: Greater Than Working with Ranges Boundary conditions determine whether the exact threshold value is included or excluded from results. Inclusive vs Exclusive The difference matters when you hit the exact boundary number. Watch how the filter checks
- IN and NOT IN for list matching (concepts: sqlInList)
List matching simplifies queries when you need to check against multiple possible values at once. If the column value matches ANY item in the list, the row is kept. Example The "food" row is the only one rejected because it does not appear in the list. Every other type matches at least one entry and passes through to the result. Why IN Is Powerful More Examples Problem: Show sales from three specific categories. Problem: Get data for four specific customer IDs. How does IN handle a longer list o
- AND for combining conditions
Example How AND Works A row only appears in results if it passes every single condition. If it fails any one check, it is excluded. Example: • User from Canada, active, logged in recently: EXCLUDED (fails country check) • User from US, inactive, logged in recently: EXCLUDED (fails status check) • User from US, active, logged in 2024: EXCLUDED (fails login date check) • User from US, active, logged in recently: INCLUDED (passes all checks) Practical Applications Which query correctly combines two