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

Daily Life
Interviews

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.

THE CASE OF THE SHRINKING TABLE

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.

employees
idnamedepartmentsalary
1ChenEngineering85000
2PatelEngineering92000
3OseiMarketing68000
4RuizSales74000
5KimEngineering78000
6TanakaMarketing71000
7AdamsSales82000
8SilvaHR76000
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.
1SELECT
2 device_id,
3 status
4FROM devices
5WHERE status = 'active'
Single Cell Where
devices
device_idstatus
device_001active
device_002inactive
device_003active
device_004pending
device_005active
result
device_idstatus
Step 1/5
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.

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.

Basic pattern:
1SELECT
2 what_you_want
3FROM table_name
4WHERE condition
Result
what_you_want
filtered_result_1
filtered_result_2

Everything after WHERE is your filter condition. The condition is a test that can be true or false for each row.

//

Example

Here is a simple example filtering students by grade.
1SELECT
2 name,
3 grade
4FROM students
5WHERE grade = 'A'
Result
namegrade
Alice JohnsonA
Diana LeeA

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

KEY RULES
  • WHERE always comes after FROM
  • You can combine multiple conditions with AND
  • If you skip WHERE, you get every row in the table
Filters are built with simple comparison operators:
=!=> < >= <=INNOT INAND
=
Values match
Checks for exact equality
!=
Values differ
Checks values don't match
> < >= <=
Compare order
Compares numbers or dates
IN
In a list
Checks value is in a list
NOT IN
Not in a list
Value is not in the list
AND
Combine rules
Joins multiple conditions
Which query correctly filters for active users?
This query is missing the WHERE keyword and will cause an error.
1SELECT *
2FROM users status = 'active'

The Equals Operator

Exact matching is the most common type of filter. The equals operator lets you find rows where a column has a specific value.
//

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

1SELECT
2 device_id,
3 status
4FROM devices
5WHERE status = 'active'
Result
device_idstatus
device_001active
device_003active
device_007active

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:

• Find a specific user by email • Get an order by order number • Show products in one category • Filter data from one region
Row-by-row check
Row-by-row check
The database examines each row individually against your condition.
Exact match only
Exact match only
Keeps rows where the values match exactly, nothing approximate.
Works with all types
Works with all types
Compares text, numbers, and dates with the same syntax.
What happens when you forget to quote a string value?
Without quotes, the database thinks "active" is a column name and raises an error.
1SELECT
2 *
3FROM orders
4WHERE status = active

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'
WHERE
LIKE
=
AND

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 (=, !=)

Daily Life
Interviews

Match or exclude rows by exact values

Sometimes you need to find everything except a specific value. The not equals operator is the inverse of exact matching.

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.

1SELECT
2 device_id,
3 status
4FROM devices
5WHERE status != 'inactive'
Single Column Operator
devices
device_idstatus
device_001active
device_002inactive
device_003active
device_004inactive
device_005pending
result
device_idstatus
Step 1/5

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

1SELECT
2 device_id,
3 status
4FROM devices
5WHERE status != 'inactive'
Result
device_idstatus
device_001active
device_003pending
device_007active
device_012maintenance

Problem: Show all devices except inactive ones. Solution: Use != to exclude "inactive". You get active, pending, and maintenance devices.

Equals and Not Equals

Understanding when to use each operator is essential. One finds matches while the other excludes them.
//

Side-by-Side Comparison

Keeps ONLY rows where status equals "active". Every other value is filtered out.
1SELECT
2 *
3FROM devices
4WHERE status = 'active'
This same pattern works for any exclusion filter. Here we exclude trial accounts to show only paying customers.
1SELECT
2 user_id,
3 account_type
4FROM users
5WHERE account_type != 'trial'
Result
user_idaccount_type
user_42premium
user_89basic
user_156enterprise

By filtering out trial accounts with !=, we get a clean list of users who have converted to paid plans.

//

Alternative Syntax: <>

In SQL, you can write "not equal to" in two ways. Both produce identical results:
!= is the more common syntax, familiar to programmers from other languages like Python, Java, and JavaScript.
1SELECT
2 *
3FROM users
4WHERE status != 'trial'

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.

Understanding the difference between equals and not-equals helps you choose the right filter.
= (Equals)
  • Keeps matching rows
  • Find a specific value
  • Most common filter
!= (Not Equals)
  • Removes matching rows
  • Exclude a specific value
  • Also written as <>
Which syntax is the SQL standard for "not equal"?
!= is common in programming languages but is not the original SQL standard.
1SELECT
2 *
3FROM devices
4WHERE status != 'inactive'
Now practice using the not-equals operator to exclude a specific status.

> Complete this query to show all orders that are not from trial accounts.

SELECT
  order_id,
  account_type
FROM orders
WHERE account_type ___ ___
'trial'
<>
'premium'
=

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.

Both equals and not equals comparisons are case-sensitive for text in most databases, so filtering for "Active" will not match rows containing "active" unless you normalize the case first.

Comparison operators (<, >)

Daily Life
Interviews

Find rows above or below a threshold

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:
1SELECT
2 *
3FROM orders
4WHERE amount > 100
Result
order_idcustomeramount
ORD001Alice150.00
ORD003Bob275.50
ORD007Carol120.00
//

Example: Greater Than

1SELECT
2 user_id,
3 total_spent
4FROM transactions
5WHERE total_spent > 500
Result
user_idtotal_spent
user_42750
user_891200
user_103685

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

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 each row against the threshold.
1SELECT
2 product_id,
3 stock
4FROM inventory
5WHERE stock <= 10
Single Column Operator
inventory
product_idstock
P0015
P00215
P00310
P0043
P0058
result
product_idstock
Step 1/5
Stock values of 10 or less pass through (5, 10, 3, 8). The value 15 is filtered out because it exceeds the threshold. Notice that 10 itself is included because the operator is <= (less than or equal).
1SELECT
2 product_id,
3 stock_level
4FROM inventory
5WHERE stock_level <= 10
Result
product_idstock_level
P0015
P02310
P0453
P0678

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

Use <= to find values at or below a threshold:
1SELECT
2 order_id,
3 total
4FROM orders
5WHERE total <= 200
Result
order_idtotal
ORD-042100
ORD-089150
ORD-203200

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."

TIP
A common mistake is using > when you mean >=. Always ask yourself: should the boundary value itself be included in the results?
• Find transactions above a threshold • Get recent records after a date • Filter products below a price point • Select items within a range
HOW IT WORKS
  • 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)
Which query includes products priced at exactly 50?
The > operator excludes the exact boundary. Products at exactly $50 are not included.
1SELECT
2 *
3FROM products
4WHERE price > 50
Try using a comparison operator to filter products by price.

> Complete this query to find products priced above $50.

SELECT
  product_id,
  ___
FROM products
WHERE price ___ 50
name
price
>
<
Comparison operators are indispensable for working with numeric columns like prices, quantities, scores, and dates, where exact equality is rarely the right filter.
The boundary value question is one of the most common sources of off-by-one errors in SQL. Always be explicit about whether you want to include or exclude the exact threshold value.

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

Daily Life
Interviews

Match rows against a list of values

List matching simplifies queries when you need to check against multiple possible values at once.

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:

1SELECT
2 *
3FROM table_name
4WHERE column_name IN (
5 'value1',
6 'value2',
7 'value3'
8 )
Result
idcolumn_name
1value1
3value2
5value3
If the column value matches ANY item in the list, the row is kept.
//

Example

1SELECT
2 id,
3 type
4FROM items
5WHERE type IN (
6 'book',
7 'tool',
8 'toy'
9 )
Result
idtype
A1book
B2tool
C3food
D4toy
E5book

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.

1SELECT
2 id,
3 type
4FROM items
5WHERE type IN (
6 'book',
7 'tool',
8 'toy'
9 )
Single Column Operator
items
idtype
A1book
B2tool
C3food
D4toy
E5book
result
idtype
Step 1/5
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

Without IN, you would need to write a separate = check for each value. IN replaces all of those with a single, clean expression.

1SELECT
2 id,
3 type
4FROM items
5WHERE type IN (
6 'book',
7 'tool',
8 'toy'
9 )
Result
idtype
A1book
B2tool
D4toy

This single IN expression checks against three values at once. Adding more values just means extending the list.

//

More Examples

1SELECT
2 product_id,
3 category,
4 revenue
5FROM sales
6WHERE category IN (
7 'Electronics',
8 'Home',
9 'Sports'
10 )
Result
product_idcategoryrevenue
P101Electronics1250
P205Home890
P312Sports450
Problem: Show sales from three specific categories.
1SELECT
2 customer_id,
3 name
4FROM customers
5WHERE customer_id IN (
6 101,
7 205,
8 312,
9 458
10 )
Result
customer_idname
101Acme Corp
205TechStart Inc
312Global Solutions
458Innovation Labs
Problem: Get data for four specific customer IDs.

The IN operator simplifies checking if a value matches any item in a list.

List membership check
List membership check
Checks if the value appears anywhere in your provided list.
Cleaner than OR chains
Cleaner than OR chains
Replaces many OR conditions with a single readable expression.
Works with all types
Works with all types
Accepts both text strings and numbers in the value list.
How does IN handle a longer list of values?
IN with three regions returns orders from North America.
1SELECT
2 *
3FROM orders
4WHERE region IN (
5 'US',
6 'CA',
7 'MX'
8 )

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

1SELECT
2 id,
3 status
4FROM orders
5WHERE status NOT IN (
6 'cancelled',
7 'refunded',
8 'failed'
9 )
Result
idstatus
ORD-001completed
ORD-003shipped
ORD-005processing
ORD-007completed
This returns all orders except those that were cancelled, refunded, or failed. The database checks each row's status against the exclusion list and returns rows that don't match any of the values.
//

Real-World Example

NOT IN is especially valuable in analytics and reporting when you need to exclude test data, invalid records, or specific categories:

1SELECT
2 product_id,
3 category,
4 sales
5FROM products
6WHERE category NOT IN (
7 'Discontinued',
8 'Sample',
9 'Internal'
10 )
Result
product_idcategorysales
P101Electronics5420
P205Home3190
P312Sports2875
This filters a sales report to show only active, customer-facing products by excluding discontinued items, samples, and internal-use products.
DATABASE EXECUTION
  • More efficient than writing separate != checks for each value
  • Optimized similarly to IN for quick membership testing
  • Useful for maintaining exclusion lists that may change over time

Compare IN and NOT IN on the same data:

IN keeps only rows matching the listed values.
1SELECT
2 *
3FROM products
4WHERE category IN (
5 'Electronics',
6 'Home'
7 )

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
LIKE
status
BETWEEN

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

Daily Life
Interviews

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

1SELECT
2 user_id,
3 country,
4 status
5FROM users
6WHERE country = 'US'
7AND status = 'active'
8AND last_login > '2025-01-01'
Result
user_idcountrystatus
user_42USactive
user_89USactive
user_156USactive

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

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

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.

SegmentsRangesRules
Segments
Target groups
Narrow by age and region
Ranges
Range + class
Pair ranges with a class
Rules
Business rules
Stack rules in one query
Which query correctly combines two conditions?
A query can only have one WHERE clause. This will cause an error.
1SELECT *
2FROM users
3WHERE country = 'US'
4WHERE status = 'active'
//

Putting It All Together

Most real queries combine several operators. Here is an example using =, >, and IN all at once:

1SELECT
2 order_id,
3 customer_id,
4 total
5FROM orders
6WHERE status = 'completed'
7AND total > 100
8AND region IN (
9 'US',
10 'CA'
11 )
Result
order_idcustomer_idtotal
ORD-101CUST-42150
ORD-203CUST-89225
ORD-405CUST-156180

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.

Do
  • 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
  • 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
PUTTING IT ALL TOGETHER

> 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.
The = 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.
KEY TAKEAWAYS
WHERE is the keyword that starts filtering and comes after FROM in a query
The = operator finds exact matches; use it when you know precisely what value you need
The != operator (or <>) excludes a specific value from results
Comparison operators (>, <, >=, <=) filter by ranges and work with numbers and dates
IN checks if a value matches any item in a list; cleaner than multiple OR conditions
NOT IN excludes rows that match any value in a list
AND combines conditions so all must be true for a row to be included
Start with simple single conditions, then combine them as your queries get more specific

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

  1. 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

  2. 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

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

  4. 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

  5. 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