Sub topic 1
Predicates in the WHERE clause
Prerequisites
This chapter assumes you can already:
- Write a basic
SELECTstatement that reads columns from one table. - Describe a table in terms of rows and columns.
- Use comparison operators such as
=,<, and>. - Combine conditions with
ANDandORin aWHEREclause.
The later chapters cover LIKE, IN, and BETWEEN one at a time. This chapter gives you the model they all share: what a predicate is, what it can evaluate to, and how WHERE uses the result.
What a predicate is
A predicate is an expression that SQL evaluates to a truth value for one row. The WHERE clause evaluates its predicate once for each row that the FROM clause produces. It keeps the row if the result is true and discards it otherwise.
You already know several predicates:
salary > 50000
department = 'Sales'Each of these takes values from the current row, compares them, and produces a result. LIKE, IN, and BETWEEN are more predicates of the same kind. They differ only in how they compare.
A sample table
The examples in this chapter use one small table. It deliberately contains NULL values. The statements run unchanged on SQLite, PostgreSQL, MySQL, and SQL Server.
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name VARCHAR(50) NOT NULL,
department VARCHAR(30),
salary INTEGER
);
INSERT INTO employees (id, name, department, salary) VALUES
(1, 'Alice', 'Sales', 52000),
(2, 'Bob', 'Support', 41000),
(3, 'Carla', 'Marketing', 68000),
(4, 'Dan', NULL, 45000),
(5, 'Anika', 'Sales', NULL);Dan has no department, and Anika has no recorded salary. In SQL, NULL means "no value is known", and it behaves differently from every ordinary value.
Three possible results
Most programming languages have two truth values. SQL has three: TRUE, FALSE, and UNKNOWN. A predicate returns UNKNOWN when it has to compare against a NULL, because the answer cannot be known. This model is called three-valued logic.
WHERE keeps a row only when the predicate is TRUE. Rows that evaluate to FALSE and rows that evaluate to UNKNOWN are both removed.
Run these queries against the sample table and compare the results:
SELECT id, name FROM employees WHERE salary > 50000;This returns Alice and Carla. Anika's salary is NULL, so NULL > 50000 is UNKNOWN and her row is discarded.
SELECT id, name FROM employees WHERE department <> 'Sales';This returns Bob and Carla. Dan is missing even though his department is clearly not 'Sales'. The comparison NULL <> 'Sales' is UNKNOWN, not TRUE.
To test for a missing value, use IS NULL or IS NOT NULL:
SELECT id, name FROM employees WHERE department IS NULL;This returns Dan. The expression department = NULL never works. It evaluates to UNKNOWN for every row, including rows where department is NULL, so it returns nothing.
The predicate families
Every predicate you write in a WHERE clause belongs to one of a few families. This tutorial covers the three that have special syntax.
| Predicate | Question it answers | Example |
|---|---|---|
| Comparison (`=`, `<>`, `<`, `>`, `<=`, `>=`) | How does this value compare to another? | `salary >= 50000` |
| `LIKE` | Does this text match a pattern? | `name LIKE 'A%'` |
| `IN` | Is this value one of a set? | `department IN ('Sales', 'Support')` |
| `BETWEEN` | Is this value inside an inclusive range? | `salary BETWEEN 40000 AND 60000` |
| `IS NULL` | Is the value missing? | `department IS NULL` |
| `EXISTS` | Does a subquery return any row? | `EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id)` |
IS NULL and EXISTS are the exceptions in this table. They always return TRUE or FALSE and never UNKNOWN. That property is why NOT EXISTS is safer than NOT IN when NULL values may be present. The chapter on NOT IN returns to this.
Here is one query that uses three of the families together:
SELECT id, name, department, salary
FROM employees
WHERE department IN ('Sales', 'Support')
AND name LIKE 'A%'
AND salary BETWEEN 40000 AND 60000;Only Alice passes all three tests. Anika is in Sales and her name starts with A, but her salary is NULL, so the BETWEEN test is UNKNOWN.
How predicates combine
You build larger predicates from smaller ones with AND, OR, and NOT. These operators work on all three truth values:
| A | B | A AND B | A OR B |
|---|---|---|---|
| TRUE | UNKNOWN | UNKNOWN | TRUE |
| FALSE | UNKNOWN | FALSE | UNKNOWN |
| UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN |
NOT UNKNOWN is still UNKNOWN. This fact explains why negated predicates such as NOT LIKE and NOT IN do not return the rows you might expect when a column contains NULL.
AND binds more tightly than OR, the way multiplication binds more tightly than addition. Without parentheses, a OR b AND c means a OR (b AND c). Use parentheses whenever you mix the two. The final chapter-length treatment is in the section on combining predicates, but this example shows the risk:
SELECT id, name, department, salary
FROM employees
WHERE department = 'Sales'
OR department = 'Support'
AND salary > 50000;SQL reads this as Sales OR (Support AND salary > 50000). It returns every Sales employee plus only the Support employees who earn more than 50000. If you meant "Sales or Support, and salary above 50000", write it with parentheses:
SELECT id, name, department, salary
FROM employees
WHERE (department = 'Sales' OR department = 'Support')
AND salary > 50000;Where WHERE sits in query processing
SQL does not run clauses in the order you write them. Logically, the database processes them in this order:
FROM(and joins) builds the set of candidate rows.WHEREfilters individual rows.GROUP BYforms groups from the remaining rows.HAVINGfilters groups.SELECTcomputes the output columns and their aliases.ORDER BYsorts the result.
Two practical consequences follow:
- A column alias defined in
SELECTis not visible inWHERE. This query fails in standard SQL becauseannualdoes not exist yet whenWHEREruns:
SELECT name, salary * 12 AS annual
FROM employees
WHERE annual > 600000;Repeat the expression instead: WHERE salary * 12 > 600000.
WHEREcannot test aggregate results such asCOUNT(*)orAVG(salary). Those do not exist until grouping happens. UseHAVINGfor conditions on groups.
The database may physically execute the query in a different order, for example by using an index. The result must still match this logical order.
Predicates and the same idea elsewhere
The predicate model is not limited to WHERE. The same expressions, with the same three-valued behavior, appear in other places:
JOIN ... ONuses a predicate to decide which pairs of rows match.HAVINGuses a predicate to decide which groups to keep.CASE WHENuses a predicate to choose a branch. A branch whose condition isUNKNOWNis not taken.CHECKconstraints use a predicate to validate data. ACHECKconstraint accepts a row when the predicate isTRUEorUNKNOWN. This is the opposite ofWHERE, and it surprises many people.
Learning the three-valued model once therefore pays off in all of these places.
Common errors
- Comparing to
NULLwith=. UseIS NULL. See the warning above. - Expecting
<>to includeNULLrows. A row with a missing value is neither equal nor unequal to anything. To include those rows, addOR column IS NULL. - Mixing
ANDandORwithout parentheses. The result is valid SQL that answers a different question. - Using a
SELECTalias inWHERE. Repeat the expression or wrap the query in a subquery. - Forgetting that text literals use single quotes.
'Sales'is a string. In standard SQL,"Sales"is an identifier, meaning a column or table name.
What comes next
The next chapters take each specialized predicate in turn. You will see LIKE with its two wildcards, IN with lists and subqueries, and BETWEEN for ranges. Each chapter returns to NULL, because every one of these predicates can produce UNKNOWN, and negating them is where most surprises happen.
Exercise
Using the sample employees table from this chapter, which names does this query return, and why are Dan and Anika missing? SELECT name FROM employees WHERE department <> 'Sales' OR salary > 50000;
Show answer
It returns Alice, Bob, and Carla. Alice qualifies because her salary 52000 is above 50000, so the OR is TRUE. Bob and Carla qualify because their departments are not 'Sales'. Dan has a NULL department, so department <> 'Sales' is UNKNOWN, and his salary 45000 is not above 50000, so salary > 50000 is FALSE. UNKNOWN OR FALSE is UNKNOWN, and WHERE discards rows that are not TRUE. Anika is in Sales, so the first test is FALSE, and her NULL salary makes the second test UNKNOWN. FALSE OR UNKNOWN is UNKNOWN, so her row is discarded too.
Exercise
Rewrite the query from the previous exercise so that Dan is also returned, without changing the result for anyone else.
Show answer
Add an IS NULL test for the department: SELECT name FROM employees WHERE department <> 'Sales' OR department IS NULL OR salary > 50000; For Dan, department IS NULL is TRUE, so the whole OR is TRUE. The other four rows behave as before, because IS NULL is FALSE for them. Anika is still excluded, since her department is not NULL and her salary is NULL.
Exercise
A query reads WHERE department = 'Sales' OR department = 'Support' AND salary > 50000. Which employees from the sample table does it return?
Show answer
It returns Alice and Anika. AND binds more tightly than OR, so the condition means department = 'Sales' OR (department = 'Support' AND salary > 50000). Alice and Anika are in Sales, so the first branch is TRUE for both, even though Anika's salary is NULL. Bob is in Support, but his salary 41000 is not above 50000, so the second branch is FALSE.