Sub topic 7
Combining conditions with AND, OR, and NOT
This chapter assumes you can write a basic SELECT ... FROM ... WHERE query and that you know the comparison operators (=, <>, <, <=, >, >=). You should also know that a table has rows and columns. The examples use an employees table with the columns first_name, last_name, department, salary, hire_date, and manager_id.
A single comparison rarely answers a real question. You usually want "Sales staff who earn at least 50,000" or "anyone except contractors." The logical operators AND, OR, and NOT join simple conditions into one larger condition. The database evaluates that condition for every row and keeps the rows where it is true.
The working model: conditions produce true, false, or unknown
Each comparison in a WHERE clause produces one of three results: true, false, or unknown. Unknown appears when a value is NULL, which marks a missing value. The next chapters cover NULL in detail. For now, remember the rule that matters here: WHERE keeps a row only when the whole condition is true. Rows where the condition is false or unknown are dropped.
The three operators work like this:
| Operator | Result is true when | Example |
|---|---|---|
| `AND` | both sides are true | `department = 'Sales' AND salary >= 50000` |
| `OR` | at least one side is true | `department = 'Sales' OR department = 'Support'` |
| `NOT` | the condition is false | `NOT department = 'Sales'` |
AND: every condition must hold
AND narrows the result. Each extra AND condition can only remove rows, never add them.
SELECT first_name, last_name, department, salary
FROM employees
WHERE department = 'Sales'
AND salary >= 50000;A row appears only if its department is exactly 'Sales' and its salary is 50,000 or more. Text values go in single quotes. Whether 'Sales' matches 'sales' depends on the database and its collation (the rules for comparing text). PostgreSQL and SQLite are case-sensitive for = by default, and MySQL usually is not.
You can chain as many conditions as you like:
SELECT first_name, last_name
FROM employees
WHERE department = 'Sales'
AND salary >= 50000
AND hire_date >= '2020-01-01';OR: at least one condition must hold
OR widens the result. A row qualifies if any one of the conditions is true.
SELECT first_name, department
FROM employees
WHERE department = 'Sales'
OR department = 'Marketing';When you test one column against several values like this, IN ('Sales', 'Marketing') is shorter. A later chapter covers IN. The OR form is still worth knowing because it also works when the conditions involve different columns.
SELECT first_name, department, salary
FROM employees
WHERE department = 'Sales'
OR salary > 100000;This returns everyone in Sales, plus anyone in any department who earns more than 100,000. A row that meets both conditions appears once, not twice.
NOT: reversing a condition
NOT turns true into false and false into true. Unknown stays unknown.
SELECT first_name, department
FROM employees
WHERE NOT department = 'Sales';For simple comparisons you can usually write the same thing with the opposite operator, which many people find easier to read:
SELECT first_name, department
FROM employees
WHERE department <> 'Sales';NOT earns its place in front of larger conditions and special predicates (conditions with their own keyword). Examples are NOT IN, NOT BETWEEN, NOT LIKE, and IS NOT NULL.
SELECT first_name, last_name
FROM employees
WHERE NOT (department = 'Sales' AND salary < 30000);This excludes only the low-paid Sales employees and keeps everyone else.
Precedence: AND binds more tightly than OR
When you mix AND and OR without parentheses, the database evaluates AND first, then OR. This is called operator precedence. It is the same idea as multiplication before addition in arithmetic. The full order, from highest to lowest, is:
- Comparisons such as
=,<,>=, and special predicates such asBETWEEN,IN, andLIKE NOTANDOR
Consider this query, which looks like it should find well-paid people in Sales or Marketing:
SELECT first_name, department, salary
FROM employees
WHERE department = 'Sales'
OR department = 'Marketing'
AND salary > 50000;Because AND goes first, the database reads it as:
SELECT first_name, department, salary
FROM employees
WHERE department = 'Sales'
OR (department = 'Marketing' AND salary > 50000);The result contains every Sales employee at any salary, plus only the Marketing employees who earn more than 50,000. That is probably not what you intended.
Add parentheses to force the grouping you want:
SELECT first_name, department, salary
FROM employees
WHERE (department = 'Sales' OR department = 'Marketing')
AND salary > 50000;Now the OR is evaluated first, and the salary test applies to both departments.
Combining NOT with other operators
NOT has higher precedence than AND and OR, so it applies only to the condition right after it unless you use parentheses. These two queries differ:
-- Not in Sales, and paid over 50,000
SELECT first_name FROM employees
WHERE NOT department = 'Sales' AND salary > 50000;
-- Not (in Sales and paid over 50,000)
SELECT first_name FROM employees
WHERE NOT (department = 'Sales' AND salary > 50000);The first query keeps non-Sales employees who earn more than 50,000. The second keeps everyone except high-paid Sales employees. That includes low-paid Sales employees and all non-Sales employees at any salary.
The two forms are related by De Morgan's laws. These rules let you rewrite a negated group:
NOT (A AND B)is the same asNOT A OR NOT B.NOT (A OR B)is the same asNOT A AND NOT B.
So the second query above is equivalent to this one:
SELECT first_name FROM employees
WHERE department <> 'Sales' OR salary <= 50000;Notice that the AND became OR and each comparison flipped. Forgetting to flip the connector is a frequent source of wrong results. The rewrite is exact only when no NULL values are involved, as the next section explains.
Three-valued logic and NULL
With NULL, the combining rules extend to unknown. These truth tables show every case:
| A | B | A AND B | A OR B |
|---|---|---|---|
| true | unknown | unknown | true |
| false | unknown | false | unknown |
| unknown | unknown | unknown | unknown |
NOT unknown is unknown. Two consequences matter in practice:
- A row where one side of an
ANDis unknown and the other is true is dropped, because the result is unknown andWHEREkeeps only true. NOT (salary > 50000)does not return rows wheresalaryisNULL. The comparison is unknown, so its negation is unknown, and the row is dropped.
Suppose an employee has salary set to NULL. Neither of these queries returns that employee:
SELECT first_name FROM employees WHERE salary > 50000;
SELECT first_name FROM employees WHERE NOT salary > 50000;If you want to include rows with missing values, test for them explicitly:
SELECT first_name, salary
FROM employees
WHERE salary <= 50000
OR salary IS NULL;Common errors
- Missing parentheses around OR. The query runs without an error but returns too many rows. Check any
WHEREclause that contains bothANDandOR. - Writing a condition like
department = 'Sales' OR 'Marketing'. Each side ofORmust be a full condition. Some databases reject this, and MySQL treats the text'Marketing'as a number and evaluates it as false, so it silently returns the wrong rows. Writedepartment = 'Sales' OR department = 'Marketing'. - Using AND where you mean OR across values of one column.
department = 'Sales' AND department = 'Marketing'can never be true, because a single column holds one value per row. The result is empty. - Applying
NOTto a group without flipping the logic. Use De Morgan's laws to check your rewrite, and run both versions on a small sample if you are unsure. - Forgetting that
NOTand comparisons skip NULL rows. AddOR column IS NULLwhen missing values should be included.
Putting it together
This query combines all three operators with grouping:
SELECT first_name, last_name, department, salary
FROM employees
WHERE (department = 'Sales' OR department = 'Marketing')
AND salary >= 50000
AND NOT (last_name = 'Smith' AND department = 'Marketing');Read it from the inside out. The first group selects two departments. The salary test applies to both. The final NOT group removes one specific combination, a Marketing employee named Smith. A row must satisfy all three top-level conditions to be returned.
Exercise
A query has the condition WHERE department = 'Support' OR department = 'Sales' AND salary > 60000. Which employees does it return, and how would you change it so the salary test applies to both departments?
Show answer
Because AND binds more tightly than OR, it returns every Support employee at any salary, plus Sales employees who earn more than 60000. To apply the salary test to both departments, add parentheses: WHERE (department = 'Support' OR department = 'Sales') AND salary > 60000.
Exercise
Rewrite WHERE NOT (salary >= 40000 OR department = 'Sales') without using NOT, using De Morgan's laws. Does the rewrite behave the same if salary can be NULL?
Show answer
WHERE salary < 40000 AND department <> 'Sales'. The OR becomes AND and each comparison is flipped. With NULL values the two forms still agree on which rows are kept, because an unknown result in either form drops the row from WHERE. The rewrite is safe here, but you should still test queries that involve NULL.