Filtering with WHERE
The WHERE clause filters which rows a query returns, based on one or more conditions evaluated against each row.
Comparison and Logical Operators
WHERE supports standard comparison operators, and conditions can be combined with AND/OR to build precise filters.
SELECT * FROM Products
WHERE Price > 100 AND Category = 'Electronics';
SELECT * FROM Orders
WHERE Status = 'Pending' OR Status = 'Processing';
SELECT * FROM Employees
WHERE Department IN ('Sales', 'Marketing');
Pattern Matching and NULL
LIKE matches text patterns using wildcards (% for any sequence, _ for a single character). NULL requires special handling — it represents "unknown", so it must be checked with IS NULL, never = NULL.
SELECT * FROM Customers
WHERE Email LIKE '%@gmail.com';
SELECT * FROM Employees
WHERE ManagerId IS NULL; -- top-level employees with no manager
Common Mistakes
- Writing
WHERE column = NULLinstead ofWHERE column IS NULL— the equals operator never matches NULL. - Forgetting parentheses when mixing AND and OR, which can change a condition's meaning due to operator precedence.
- Using
LIKE '%text%'on very large tables without an appropriate index, which can be slow. - Case-sensitivity assumptions — T-SQL's default collation is often case-insensitive, which can surprise developers coming from other languages.
Professional Tip
When combining AND and OR in the same WHERE clause, use parentheses to make your intent explicit: WHERE (Status = 'Pending' OR Status = 'Processing') AND Total > 500 — this avoids relying on precedence rules that are easy to misremember.
Your Turn
Write a query that finds all orders with a status of 'Shipped' or 'Delivered', a total greater than 200, placed by a customer whose email ends in '.co.za'.
Mini Quiz
What is the correct way to check for NULL values in a WHERE clause?
IS NULL (or IS NOT NULL) is the required syntax.