Sub topic 6
NULL Propagation in Arithmetic and String Expressions
This chapter assumes you can write basic SELECT and WHERE queries, and that you know the three-valued logic from the earlier chapters: a comparison with NULL gives UNKNOWN, not FALSE. Here you will see how NULL behaves inside expressions that compute values, such as sums, products and concatenated text.
All examples use the employees table from the first chapter. Ada and Cy have a NULL commission, and Ada has a NULL manager_id.
The propagation rule
In an arithmetic expression, if any operand is NULL, the result is NULL. This is called NULL propagation. The reasoning follows from what NULL means. If you do not know one of the inputs, you cannot know the output.
SELECT 1 + NULL AS a, -- NULL
NULL * 10 AS b, -- NULL
5 - NULL AS c, -- NULL
-NULL AS d; -- NULLSome engines require a type on a bare NULL, for example CAST(NULL AS INTEGER). Table columns already have a type, so this rarely matters in real queries.
The rule holds for every arithmetic operator: +, -, *, / and %. It also holds when the result looks obvious to a human. In particular, NULL * 0 is NULL, not 0. The database does not simplify the expression, because the unknown value might be anything, and for many types and operators the answer would depend on it.
A worked example
Suppose every employee has a base pay of 1000, and commission is added on top.
SELECT name,
commission,
1000 + commission AS total_pay
FROM employees;| name | commission | total_pay |
|---|---|---|
| Ada | NULL | NULL |
| Ben | 100.00 | 1100.00 |
| Cy | NULL | NULL |
| Di | 300.00 | 1300.00 |
Ada and Cy have a base pay, but the query reports no total. The missing commission has wiped out the whole result. This is the usual bug: a report shows blanks where you expected a number.
Where to put COALESCE
You have two places to handle the NULL: around one operand, or around the whole expression.
-- Around the operand: a missing commission counts as 0.
SELECT name, 1000 + COALESCE(commission, 0) AS total_pay
FROM employees;
-- Around the whole expression: hides the missing value AND the base pay.
SELECT name, COALESCE(1000 + commission, 0) AS total_pay
FROM employees;The first query gives Ada 1000 and Cy 1000. The second gives them 0, which is wrong, because it discards a known base pay along with the unknown commission. Put COALESCE as close as possible to the nullable operand, and only substitute a value that is correct for that operand's meaning. A missing commission can reasonably be 0. A missing exchange rate cannot.
Propagation reaches comparisons
A computed NULL stays NULL when you compare it. The comparison then yields UNKNOWN, and WHERE discards those rows.
-- Returns Ben and Di only; Ada and Cy are dropped silently.
SELECT name FROM employees
WHERE commission + 50 > 100;
-- Returns Ben only (150 > 100 is TRUE, 350 > 100 is TRUE, so Di too).
-- Ada and Cy are still absent, even for the opposite test:
SELECT name FROM employees
WHERE NOT (commission + 50 > 100); -- returns no rowsThe second query returns nothing. For Ada and Cy the inner comparison is UNKNOWN, and NOT UNKNOWN is still UNKNOWN. Ben and Di make the inner comparison TRUE, so NOT makes it FALSE. A filter and its negation do not together cover every row.
String expressions
The standard SQL concatenation operator is ||, and it propagates NULL like arithmetic does.
SELECT e.name || ' reports to ' || m.name AS description
FROM employees e
LEFT JOIN employees m ON m.id = e.manager_id;| description |
|---|
| NULL |
| Ben reports to Ada |
| Cy reports to Ada |
| Di reports to Ben |
Ada has no manager, so the LEFT JOIN gives m.name as NULL, and the entire sentence becomes NULL. Note that one NULL operand removes the whole string, including the parts that were known. The fix is again a substitute for the nullable operand:
SELECT e.name || ' reports to ' || COALESCE(m.name, 'nobody') AS description
FROM employees e
LEFT JOIN employees m ON m.id = e.manager_id;Ada's row now reads Ada reports to nobody.
Functions that handle NULL differently
Most scalar functions return NULL when an argument is NULL. Examples are UPPER, LENGTH, ABS, ROUND and SUBSTRING. Functions of this kind are sometimes called strict. The exceptions are the ones designed for NULL, such as COALESCE, NULLIF and IS NULL. Several concatenation functions are also exceptions, and this is where engines disagree.
| System | `a \ | \ | NULL` or `a + NULL` | `CONCAT(a, NULL)` |
|---|---|---|---|---|
| PostgreSQL | NULL | `a` (NULL treated as empty) | ||
| SQL Server | `a + NULL` is NULL by default | `a` (NULL treated as empty) | ||
| MySQL | `\ | \ | ` is logical OR by default; use `CONCAT` | NULL |
| Oracle | `a` (empty string is NULL, so it is skipped) | `a` | ||
| SQLite | NULL | `a` in 3.44 and later; the function is absent before that |
Check your system's documentation before relying on any of these. Code that moves between engines is safest when it writes COALESCE explicitly, because that behaves the same everywhere.
Oracle deserves a second note. It treats the empty string '' as NULL, so LENGTH('') returns NULL there. In PostgreSQL, SQL Server, MySQL and SQLite, LENGTH('') returns 0, and an empty string is a real value distinct from NULL.
How the evaluation proceeds
An expression is evaluated from the inside out. NULL entering at any leaf passes up through every operator that is strict, until something handles it.
Common errors
| Mistake | What happens | Better approach | Column | Column |
|---|---|---|---|---|
| Assuming `NULL * 0` is 0 | The result is NULL | Substitute the operand first if 0 is the right meaning | ||
| Wrapping the whole expression in `COALESCE` | Known values are discarded along with the unknown one | Wrap only the nullable operand | ||
| Building a label with `\ | \ | ` over nullable columns | Entire label becomes NULL | `COALESCE` each nullable part, or use `CONCAT_WS` where available |
| Filtering on `col + 1 > x` and its negation, expecting full coverage | Rows with NULL appear in neither result | Handle NULL explicitly with `IS NULL` | ||
| Replacing NULL with 0 in a column where 0 has meaning | Reports treat unknown as a measured zero | Keep NULL, or use a documented sentinel |
Edge cases
- Type of the substitute.
COALESCEneeds a compatible type.COALESCE(commission, 'none')fails or forces a text conversion in most systems, becausecommissionis numeric. UseCAST(commission AS VARCHAR(20))first if you need a text placeholder. - Division.
x / NULLandNULL / xare NULL. Division by zero is a different case: it usually raises an error.NULLIF(divisor, 0)turns it into NULL, as shown in an earlier chapter, and the propagation rule then makes the whole quotient NULL. - Chained expressions. Each stage can add its own NULL. A formula like
(a + b) * c / dis NULL if any of the four is NULL, so check every input when a result is unexpectedly blank. - Unary and comparison operators.
-x,x BETWEEN 1 AND 5andx LIKE 'A%'all return NULL or UNKNOWN whenxis NULL.
Exercise
Using the employees table, what does SELECT name, commission * 0 AS zeroed FROM employees return for Ada and for Ben? Then write a version that returns 0 for Ada.
Show answer
Ada gets NULL, because Ada's commission is NULL and NULL 0 is NULL. Ben gets 0.00, since 100.00 0 is 0. To get 0 for Ada, replace the NULL operand first: SELECT name, COALESCE(commission, 0) * 0 AS zeroed FROM employees.
Exercise
A colleague writes SELECT name, COALESCE(1000 + commission, 0) AS total_pay FROM employees. Which employees get a wrong value, and what is the correct value for each?
Show answer
Ada and Cy get 0, but their correct total is 1000, because their base pay is known and only the commission is missing. The correct query is SELECT name, 1000 + COALESCE(commission, 0) AS total_pay FROM employees.
Exercise
In PostgreSQL, SELECT e.name || ' manages ' || m.name FROM employees e LEFT JOIN employees m ON m.manager_id = e.id returns NULL for some rows. Which employees produce a NULL row, and why?
Show answer
Cy produces a NULL row, because Cy manages nobody. The LEFT JOIN finds no matching m row, so m.name is NULL and || propagates it to the whole string. Ada and Ben each match at least one report, and Di manages nobody, so Di also gives NULL. Ada's join matches Ben and Cy, giving two rows ('Ada manages Ben' and 'Ada manages Cy'), and Ben's matches Di.