01 / 21

SQL WHERE
Filtering

Learn how to select exactly the rows you need using comparisons, boolean logic, and powerful filter conditions in SQL.

SQL

What Is Filtering?

A database table might have thousands or millions of rows. Most of the time, you only care about a small subset. Filtering means telling the database: "give me only the rows that match these conditions."

The WHERE Clause

WHERE is the keyword you add after the table name in a SELECT statement. It defines a condition that every returned row must satisfy.

SELECT column1, column2 FROM table_name WHERE condition;

How WHERE Processes Rows

All Rows Alice | age 17 Bob | age 22 Carol | age 15 Dan | age 19 Eve | age 30 WHERE
\(age \ge 18\)
Filtered Rows Bob | age 22 Dan | age 19 Eve | age 30 Alice | age 17 Carol | age 15 excluded (condition = false) 3 rows returned

Comparison Operators

SQL provides six comparison operators to test a column value against a literal or another column:

Operator Meaning Example
\(=\)Equal to\(\text{age} = 18\)
\(!=\) or \(<>\)Not equal\(\text{status} != \text{'active'}\)
\(<\)Less than\(\text{price} < 50\)
\(>\)Greater than\(\text{score} > 90\)
\(\le\)Less than or equal\(\text{qty} \le 100\)
\(\ge\)Greater than or equal\(\text{grade} \ge \text{'B'}\)

Boolean Logic: AND, OR, NOT

Combine multiple conditions with boolean operators to build precise filters:

AND
Both conditions must be true. Narrows results.
OR
At least one condition must be true. Widens results.
NOT
Inverts the condition. True becomes false and vice versa.

AND vs OR: Visual Comparison

AND Both must be true Result A B OR Either can be true A B Result Everything shaded is included

WHERE vs HAVING

Both filter rows, but they operate at different stages of query execution:

Feature WHERE HAVING
FiltersIndividual rowsGroups (after GROUP BY)
RunsBefore groupingAfter grouping
Aggregates?Cannot use SUM, COUNT, etc.Can use aggregates
Example\(\text{WHERE age} > 18\)\(\text{HAVING COUNT}(*) > 5\)

Special WHERE Operators

BETWEEN
Tests if a value is in a range (inclusive). Example: age BETWEEN 18 AND 25
IN
Tests if a value matches any item in a list. Example: color IN ('red', 'blue')
LIKE
Pattern matching with % (any chars) and _ (single char). Example: name LIKE 'A%'
IS NULL
Checks for missing values. Never use \(=\) NULL: always use IS NULL or IS NOT NULL.

How to Build a WHERE Filter

1
Identify the goal. What subset of rows do you need? Translate the English question into conditions.
2
Pick the right operator. Equality (\(=\)), range (BETWEEN), pattern (LIKE), or set membership (IN)?
3
Combine with AND / OR. Use AND when all conditions must hold. Use OR when any condition suffices.
4
Add parentheses. Group conditions explicitly so the precedence is clear and correct.
5
Test with a small dataset. Run the query and verify the output matches what you expected.

Example 1: Simple Comparison

Task: Find all students who scored above 85 on their exam.

SELECT name, score FROM students WHERE score > 85;

Example 2: Multiple Conditions

Task: Find products that cost under $50 and are in the "Electronics" category.

SELECT product_name, price, category FROM products WHERE price < 50 AND category = 'Electronics';

Example 3: Complex Boolean Logic

Task: Find employees in the "Sales" or "Marketing" department who were hired after 2020.

SELECT name, department, hire_date FROM employees WHERE (department = 'Sales' OR department = 'Marketing') AND hire_date > '2020-01-01';

Example 4: IN and BETWEEN

Task: Find orders placed between January and March 2024 for customers in New York, Chicago, or Miami.

SELECT order_id, customer_city, order_date FROM orders WHERE order_date BETWEEN '2024-01-01' AND '2024-03-31' AND customer_city IN ('New York', 'Chicago', 'Miami');

Common Mistakes

✕ Using \(=\) NULL
NULL is unknown, not a value. \(=\) NULL always returns false. Use IS NULL instead.
✕ Missing Parentheses
AND binds tighter than OR. Without parentheses, A OR B AND C means A OR (B AND C), not (A OR B) AND C.
✕ Wrong String Quotes
SQL strings use single quotes ('text'). Double quotes are for identifiers in most databases. Using the wrong type causes errors.

WHERE Cheat Sheet

Pattern Syntax Use When
Exact matchcol = valueYou know the exact value
Rangecol BETWEEN a AND bValue falls within bounds
Set membershipcol IN (v1, v2, ...)Value is one of several options
Patterncol LIKE 'pattern'Partial text matching
Missing datacol IS NULLChecking for absent values
Combinecond1 AND cond2All conditions must hold
Alternatecond1 OR cond2Any condition suffices
NegateNOT conditionExclude matching rows

Question 1 of 5

Which SQL keyword is used to filter rows based on a condition?

Question 2 of 5

What does the following query return?
SELECT * FROM users WHERE age \(\ge\) 18 AND status = 'active';

Question 3 of 5

How do you correctly check for missing (NULL) values in a column?

Question 4 of 5

Given: WHERE dept = 'HR' OR dept = 'Finance' AND salary \(>\) 50000
Without parentheses, which rows are returned?

Question 5 of 5

Which query correctly finds products priced between $10 and $50 that are not in the "Toys" category?