Sub topic 12
Combining Predicates and Operator Precedence
A real filter usually joins several conditions: a pattern match, a membership test, and a range, all in one WHERE clause. This chapter explains how the database groups those conditions, why the grouping often differs from what you meant, and how NULL affects the result. It assumes you can write a basic SELECT, use comparison operators, and use AND and OR in a WHERE clause. It also assumes you have met LIKE, IN, and BETWEEN in the earlier chapters.
Every predicate is a boolean expression
A predicate such as name LIKE 'A%', department IN ('Sales', 'Support'), or salary BETWEEN 40000 AND 60000 produces one of three values: TRUE, FALSE, or UNKNOWN. UNKNOWN appears when a NULL is involved. WHERE keeps a row only when the whole expression evaluates to TRUE.
The operators AND, OR, and NOT combine these values. Before they can do that, the database must decide which predicates each operator applies to. Precedence rules make that decision.
The precedence order
From tightest to loosest binding, the relevant operators are:
- Comparison and predicate operators:
=,<>,<,>,LIKE,IN,BETWEEN,IS NULL NOTANDOR
AND binds more tightly than OR, in the same way that multiplication binds more tightly than addition. Operators at the same level are evaluated left to right.
The classic mistake
Suppose you want Sales or Support staff who earn more than 50000. This query does not do that:
SELECT id, name, department, salary
FROM employees
WHERE department = 'Sales'
OR department = 'Support'
AND salary > 50000;Because AND binds first, the database reads it as:
WHERE department = 'Sales'
OR (department = 'Support' AND salary > 50000)It returns every Sales employee regardless of salary, plus the well-paid Support employees. Nothing raises an error, so the wrong result can go unnoticed. The fix is to say what you mean:
SELECT id, name, department, salary
FROM employees
WHERE department IN ('Sales', 'Support')
AND salary > 50000;Using IN removes the OR entirely. When you cannot remove it, add parentheses.
Parentheses are free
Parentheses cost nothing at run time and make the intent obvious to the next reader. This query from the topic's examples mixes all three predicates:
SELECT id, name, department, salary
FROM employees
WHERE department IN ('Sales', 'Support')
AND (name LIKE 'A%' OR salary BETWEEN 40000 AND 60000);The parentheses make the OR apply only to the name and salary conditions. Without them, the query would read as (department IN (...) AND name LIKE 'A%') OR salary BETWEEN .... That version returns anyone in any department whose salary is in the range.
A useful habit is to parenthesize any OR that sits next to an AND, even when the default grouping happens to match your intent.
BETWEEN has its own AND
BETWEEN low AND high uses the word AND as part of its syntax. That AND is not a logical operator. The database pairs it with BETWEEN first, so this query behaves as you would expect:
SELECT id, name
FROM employees
WHERE salary BETWEEN 40000 AND 60000
AND department = 'Sales';The first AND belongs to BETWEEN, and the second is the logical operator. Reading BETWEEN 40000 AND 60000 as one unit helps you avoid miscounting. Do not try to place an expression such as x OR y in the middle of the bounds. Keep the bounds simple values or arithmetic expressions.
NOT and its scope
NOT binds tighter than AND and OR, but looser than the predicates. These two forms are the same:
WHERE NOT name LIKE 'A%'
WHERE NOT (name LIKE 'A%')NOT negates only the predicate that follows it. To negate a combination, you need parentheses:
SELECT id, name, department
FROM employees
WHERE NOT (department IN ('Sales', 'Support') AND name LIKE 'A%');This keeps every row except the Sales or Support employees whose names start with A.
The negated predicate forms, NOT LIKE, NOT IN, and NOT BETWEEN, can be written in either position. name NOT LIKE 'A%' and NOT name LIKE 'A%' mean the same thing. Most people prefer the first form because it reads like a sentence.
De Morgan's laws
To rewrite a negated combination, flip each operator and negate each part:
| Original | Equivalent |
|---|---|
| `NOT (a AND b)` | `NOT a OR NOT b` |
| `NOT (a OR b)` | `NOT a AND NOT b` |
So the query above can also be written as:
SELECT id, name, department
FROM employees
WHERE department NOT IN ('Sales', 'Support')
OR name NOT LIKE 'A%';These laws hold in three-valued logic as well, so the two forms return the same rows even when NULL is present.
How NULL flows through AND, OR, and NOT
A comparison with NULL yields UNKNOWN, not FALSE. The logical operators then follow these tables:
| a | b | a AND b | a OR b |
|---|---|---|---|
| TRUE | UNKNOWN | UNKNOWN | TRUE |
| FALSE | UNKNOWN | FALSE | UNKNOWN |
| UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN |
| a | NOT a |
|---|---|
| TRUE | FALSE |
| FALSE | TRUE |
| UNKNOWN | UNKNOWN |
Two rules cover most cases. A single FALSE makes an AND FALSE, and a single TRUE makes an OR TRUE. Everything else involving UNKNOWN stays UNKNOWN. Since WHERE keeps only TRUE, UNKNOWN rows are dropped, just like FALSE rows.
Consider this query, where some employees have a NULL salary:
SELECT id, name, department, salary
FROM employees
WHERE department = 'Sales'
OR salary > 50000;| department | salary | department = 'Sales' | salary > 50000 | Result |
|---|---|---|---|---|
| Sales | NULL | TRUE | UNKNOWN | TRUE, kept |
| Support | NULL | FALSE | UNKNOWN | UNKNOWN, dropped |
| Support | 60000 | FALSE | TRUE | TRUE, kept |
The Sales employee with no salary is returned. The Support employee with no salary is not.
The negation trap
Negating an UNKNOWN gives UNKNOWN again, so negation does not bring NULL rows back. This query does not return employees with no department:
SELECT id, name
FROM employees
WHERE NOT (department = 'Sales');If department is NULL, then department = 'Sales' is UNKNOWN, and NOT UNKNOWN is also UNKNOWN. If you want those rows, say so explicitly:
SELECT id, name
FROM employees
WHERE department <> 'Sales'
OR department IS NULL;The same effect explains why NOT IN can return no rows when the list or subquery contains a NULL. The NOT EXISTS form shown in the previous chapter avoids it.
Evaluation order is not guaranteed
SQL does not promise that conditions are checked left to right. The optimizer may reorder them, and some databases may evaluate both sides of an AND even when the first is FALSE. Do not rely on one condition to protect another. This query can fail with a division-by-zero error on some systems:
SELECT id
FROM order_lines
WHERE quantity <> 0
AND total / quantity > 10;Make the second condition safe in its own right:
SELECT id
FROM order_lines
WHERE total / NULLIF(quantity, 0) > 10;NULLIF(quantity, 0) returns NULL when quantity is 0. The division then yields NULL, the comparison is UNKNOWN, and the row is dropped without an error.
Optional filters
Applications often build one query for several optional filters. A common pattern looks like this:
SELECT id, name, department
FROM employees
WHERE (:dept IS NULL OR department = :dept)
AND (:pattern IS NULL OR name LIKE :pattern);The parentheses are required. Without them, the OR and AND would regroup and the filters would stop working independently. This pattern can also stop the optimizer from choosing an index, because the plan must work for every parameter value. For hot queries, build the WHERE clause in application code so it contains only the filters that were supplied.
Combining predicates and indexes
The way you combine predicates affects which indexes can help:
ANDof conditions on indexed columns is usually good news. The optimizer can use the most selective index, or a composite index that covers several of the columns.ORacross different columns is harder. Many optimizers fall back to scanning the table unless they can combine two index lookups. If this is slow, rewriting the query as two queries joined withUNION ALLcan help, but check that no row matches both conditions so you do not get duplicates.ORon the same column is usually better written asIN. Both are the same logically, andINis easier for the optimizer to turn into a set of index lookups.- Wrapping a column in a function, such as
LOWER(name), stops ordinary index use on that column, whatever it is combined with.
A checklist for reading a compound filter
- Circle every
OR. If anANDis adjacent, decide whether parentheses are needed. - Keep the
ANDinsideBETWEENseparate from the logicalAND. - Replace
ORchains on one column withIN. - For each column that may contain
NULL, ask what happens in the UNKNOWN case, especially underNOT. - Never rely on left-to-right evaluation to prevent errors.
Exercise
A query reads WHERE department = 'Sales' OR department = 'Support' AND salary > 50000. Which rows does it return, and how would you change it so that the salary condition applies to both departments?
Show answer
Because AND binds tighter than OR, it returns all Sales employees (any salary) plus Support employees with salary above 50000. Rewrite it as WHERE department IN ('Sales', 'Support') AND salary > 50000, or add parentheses around the two department tests.
Exercise
The table has a row with department = 'Sales' and salary = NULL, and a row with department = 'Support' and salary = NULL. Which of them does WHERE department = 'Sales' OR salary > 50000 return, and why?
Show answer
Only the Sales row. For it, the expression is TRUE OR UNKNOWN, which is TRUE. For the Support row it is FALSE OR UNKNOWN, which is UNKNOWN, and WHERE keeps only TRUE rows.
Exercise
Rewrite WHERE NOT (department IN ('Sales', 'Support') AND name LIKE 'A%') without a NOT in front of the parentheses.
Show answer
WHERE department NOT IN ('Sales', 'Support') OR name NOT LIKE 'A%'. De Morgan's law turns NOT (a AND b) into NOT a OR NOT b.