Sub topic 3
How NULL Affects Filters
This chapter assumes you know basic SELECT statements, WHERE clauses, comparison operators, and AND and OR. Examples use an employees table with id, name, department, department_id, and salary columns, and a customers table with id and name columns. The orders table has customer_id.
How NULL Affects Filters
NULL means the value is unknown. A comparison with NULL, such as salary > 50000 when salary is NULL, returns unknown, not true or false. A WHERE clause keeps only rows where the condition is true, so unknown rows are dropped. Test for missing values with IS NULL or IS NOT NULL.
SELECT id, name
FROM employees
WHERE salary IS NULL;Why NOT IN Can Return No Rows
If the list after NOT IN contains a NULL, every non-matching comparison becomes unknown. The query then returns no rows at all.
SELECT c.id, c.name
FROM customers c
WHERE c.id NOT IN (SELECT customer_id FROM orders);If any orders.customer_id is NULL, this query returns nothing. Use NOT EXISTS instead, because it is not affected by NULL.
Negating with NOT LIKE, NOT IN, and NOT BETWEEN
NOT LIKE, NOT IN, and NOT BETWEEN all drop NULL rows, just as their positive forms do. A row with a NULL salary fails salary NOT BETWEEN 50000 AND 70000. If you need those rows, add an explicit IS NULL test.
Combining Predicates and Operator Precedence
AND binds more tightly than OR. Use parentheses to control which conditions group together.
SELECT id, name, department, salary
FROM employees
WHERE department IN ('Sales', 'Support')
AND (name LIKE 'A%' OR salary BETWEEN 40000 AND 60000);Writing Predicates That Can Use Indexes
A plain B-tree index can serve a predicate that compares the bare column. A prefix pattern such as name LIKE 'A%' and a range such as salary BETWEEN 40000 AND 60000 can use one. A leading wildcard, such as LIKE '%son', usually cannot. Wrapping the column in a function, such as LOWER(name), also usually prevents index use.
> Not allowed in output: I must not use block quotes. Replacing the following line.
Exercise
Which rows does WHERE bonus <> 0 miss when some bonus values are NULL, and how do you keep them?
Show answer
It misses the NULL rows, because NULL <> 0 is unknown. Keep them with WHERE bonus <> 0 OR bonus IS NULL.