Sub topic 4
How NULL behaves in expressions
This chapter assumes you can write basic SELECT ... FROM ... WHERE queries, know the common column types (numbers, text, dates), and have used GROUP BY with COUNT and SUM. It covers how NULL moves through arithmetic, string operations, comparisons, and boolean logic, and the mistakes that follow from it. The next chapter covers COALESCE and NULLIF, which are the standard tools for handling these cases.
What NULL means
NULL is a marker for a missing or unknown value. It is not zero, not an empty string, and not the text 'NULL'. A commission of 0 means "this employee earns no commission". A commission of NULL means "we do not know, or it does not apply".
This distinction explains most NULL behavior. If a value is unknown, any calculation that depends on it is also unknown. SQL models this with three-valued logic: an expression can be true, false, or unknown. A comparison or condition that depends on NULL usually yields unknown.
The examples in this chapter use this table:
CREATE TABLE employees (
employee_id INTEGER PRIMARY KEY,
first_name VARCHAR(50),
salary INTEGER,
commission INTEGER,
manager_id INTEGER
);
INSERT INTO employees VALUES (1, 'Ana', 5000, 500, NULL);
INSERT INTO employees VALUES (2, 'Ben', 4000, NULL, 1);
INSERT INTO employees VALUES (3, 'Chloe', 4500, 0, 1);
INSERT INTO employees VALUES (4, 'Dev', NULL, NULL, 2);NULL in arithmetic
If any operand of an arithmetic operator is NULL, the result is NULL. This holds for +, -, *, /, and %.
SELECT first_name,
salary,
commission,
salary + commission AS total_pay
FROM employees;| first_name | salary | commission | total_pay |
|---|---|---|---|
| Ana | 5000 | 500 | 5500 |
| Ben | 4000 | NULL | NULL |
| Chloe | 4500 | 0 | 4500 |
| Dev | NULL | NULL | NULL |
Ben has a salary, but his total pay is NULL because one operand is unknown. Chloe's 0 commission behaves normally, which shows the difference between zero and NULL.
Even operations that look like they have only one possible answer return NULL. NULL * 0 is NULL, not 0. NULL - NULL is NULL, not 0.
NULL in string operations
Text operators follow the same rule in standard SQL. Concatenating anything with NULL with the || operator gives NULL.
SELECT first_name || ' earns ' || commission AS note
FROM employees;Ben's row returns NULL instead of a partial sentence. Dialects differ here. Oracle treats the empty string '' as NULL, so 'abc' || '' is 'abc' there, and an empty string can also appear as NULL in a test. MySQL's CONCAT() function returns NULL if any argument is NULL, while CONCAT_WS() skips NULL arguments. PostgreSQL's CONCAT() ignores NULL arguments, but its || operator does not. Check your database before relying on any of these.
NULL in comparisons
Comparison operators (=, <>, <, >, <=, >=) return unknown when either side is NULL. This includes comparing NULL to NULL.
SELECT NULL = NULL AS equal_test,
NULL <> NULL AS not_equal_test,
NULL > 5 AS greater_test;All three columns are unknown, shown as NULL. (Some databases, such as Oracle, require FROM dual for a SELECT with no table.) Neither NULL = NULL nor NULL <> NULL is true. Two unknown values are not known to be equal, and they are not known to be different either.
To test for NULL, use IS NULL and IS NOT NULL. These are the only predicates that always return true or false, never unknown.
SELECT first_name
FROM employees
WHERE commission IS NULL;This returns Ben and Dev. The query WHERE commission = NULL returns no rows, and it does not raise an error, which makes the mistake easy to miss.
Three-valued logic in WHERE
A WHERE clause keeps a row only when its condition is true. Rows where the condition is false or unknown are both discarded. This is where unknown results cause surprises.
SELECT first_name
FROM employees
WHERE commission <> 500;This returns only Chloe, whose commission is 0. Ben and Dev are missing because NULL <> 500 is unknown, not true. If you want them included, say so explicitly:
SELECT first_name
FROM employees
WHERE commission <> 500
OR commission IS NULL;AND, OR, and NOT
Boolean operators follow the truth tables for three values. The important cases are the ones where the answer is known despite an unknown operand.
| a | b | a AND b | a OR b |
|---|---|---|---|
| true | unknown | unknown | true |
| false | unknown | false | unknown |
| unknown | unknown | unknown | unknown |
NOT unknown is unknown. So NOT (commission = 500) does not return Ben or Dev either, and negating a condition does not give you the complementary set of rows when NULL is present.
SELECT first_name
FROM employees
WHERE salary > 4200
OR commission IS NULL;For Dev, salary > 4200 is unknown and commission IS NULL is true. Unknown OR true is true, so Dev is returned. The row is kept because one side is definitely true.
NULL with IN and NOT IN
IN is shorthand for a chain of OR comparisons, so NULL in the list matters. x IN (1, 2, NULL) is true if x is 1 or 2, and otherwise unknown, never false.
NOT IN is where this causes real bugs. x NOT IN (1, 2, NULL) expands to x <> 1 AND x <> 2 AND x <> NULL. The last term is always unknown, so the whole expression can never be true.
SELECT first_name
FROM employees
WHERE employee_id NOT IN (SELECT manager_id FROM employees);The subquery returns NULL for Ana, who has no manager. The result is an empty set, even though Chloe and Dev manage nobody. Two common fixes:
SELECT first_name
FROM employees
WHERE employee_id NOT IN (
SELECT manager_id
FROM employees
WHERE manager_id IS NOT NULL
);SELECT e.first_name
FROM employees AS e
WHERE NOT EXISTS (
SELECT 1
FROM employees AS m
WHERE m.manager_id = e.employee_id
);Both return Chloe and Dev. NOT EXISTS is usually the safer habit because it does not depend on the subquery column being non-null.
NULL in aggregates and grouping
Aggregate functions ignore NULL inputs, with one exception: COUNT(*) counts rows, not values.
SELECT COUNT(*) AS row_count,
COUNT(commission) AS commission_count,
SUM(commission) AS commission_sum,
AVG(commission) AS commission_avg
FROM employees;| row_count | commission_count | commission_sum | commission_avg |
|---|---|---|---|
| 4 | 2 | 500 | 250 |
AVG divides 500 by the 2 non-null values, so the result is 250, not 125. If you want missing values counted as zero, you must say so, which is the job of COALESCE in the next chapter. If every input is NULL, or there are no rows, SUM and AVG return NULL, while COUNT returns 0.
For GROUP BY, DISTINCT, and UNION, two NULL values are treated as the same. This is a deliberate exception: grouping puts all NULL rows in one group, even though NULL = NULL is not true in a comparison.
NULL and sorting
The standard does not say whether NULL sorts before or after other values. Databases differ:
| Database | Default in ascending order |
|---|---|
| PostgreSQL | NULLs last |
| Oracle | NULLs last |
| MySQL | NULLs first |
| SQL Server | NULLs first |
| SQLite | NULLs first |
PostgreSQL, Oracle, and SQLite (3.30 and later) support NULLS FIRST and NULLS LAST to control this. In MySQL and SQL Server, you can sort on an expression such as commission IS NULL first, which orders non-null rows before null ones.
Checking for NULL-safe equality
Sometimes you want two values to match when both are NULL. Standard SQL provides IS NOT DISTINCT FROM, which treats two NULL values as equal and NULL versus a value as different.
SELECT a.employee_id, b.employee_id AS other_id
FROM employees AS a
JOIN employees AS b
ON a.commission IS NOT DISTINCT FROM b.commission
AND a.employee_id < b.employee_id;PostgreSQL, SQLite, and recent versions of other databases support this form. MySQL uses <=> for the same purpose. Where neither is available, write the long form: (a = b OR (a IS NULL AND b IS NULL)).
Common errors
- Writing
= NULLor<> NULL. These never return true. UseIS NULLandIS NOT NULL. - Using
NOT INwith a subquery that can returnNULL. Filter theNULLout or useNOT EXISTS. - Assuming
NULLmeans zero in arithmetic. A singleNULLmakes the whole expressionNULL. - Expecting
NOT (x = 5)to return every row wherexis not 5. Rows wherexisNULLare excluded from both. - Assuming
AVGcounts missing values as zero. It averages only the non-null ones.
Exercise
Using the employees table above, what does SELECT COUNT(*) FROM employees WHERE salary <> 4000 OR commission <> 0 return, and why?
Show answer
It returns 1. Row by row: Ana has salary 5000, so salary <> 4000 is true and the row is kept. Ben has salary 4000, so the first test is false, and commission <> 0 is unknown because his commission is NULL. False OR unknown is unknown, so Ben is dropped. Chloe has salary 4500, so the first test is true and her row is kept. Dev has NULL for both, so unknown OR unknown is unknown and Dev is dropped. That gives 2 rows kept: Ana and Chloe. Correct answer: 2, not 1.
Exercise
A query SELECT first_name FROM employees WHERE employee_id NOT IN (SELECT manager_id FROM employees) returns no rows. Explain the cause and write a fix that returns the employees who manage nobody.
Show answer
The subquery returns NULL for Ana, whose managerid is NULL. NOT IN expands to a chain of <> tests joined by AND, and the test against NULL is always unknown, so the whole condition can never be true. One fix is to add `WHERE managerid IS NOT NULL to the subquery. Another is WHERE NOT EXISTS (SELECT 1 FROM employees AS m WHERE m.managerid = employees.employeeid)`. Both return Chloe and Dev.