Sub topic 7
Replacing and Creating NULLs with COALESCE and NULLIF
This chapter assumes you know the earlier ideas in this tutorial: NULL means "no value", comparisons with NULL give UNKNOWN, and IS NULL is the way to test for it. Here you will use two standard functions to work with NULLs. COALESCE removes NULLs by substituting a value. NULLIF creates NULLs on purpose. They are small functions, but the choices you make with them change query results.
All examples use the employees table from earlier in the tutorial. Ada has no manager. Ada and Cy have no commission.
COALESCE: the first non-NULL value
COALESCE takes two or more arguments. It returns the first one that is not NULL, reading left to right. If every argument is NULL, it returns NULL.
SELECT name,
commission,
COALESCE(commission, 0) AS commission_or_zero
FROM employees
ORDER BY id;| name | commission | commission_or_zero |
|---|---|---|
| Ada | NULL | 0.00 |
| Ben | 100.00 | 100.00 |
| Cy | NULL | 0.00 |
| Di | 300.00 | 300.00 |
The flow below shows how the function decides.
Chains of fallbacks
With more than two arguments, you can list several sources in order of preference. A common case is a label built from an outer join:
SELECT e.name,
COALESCE(m.name, 'no manager') AS manager
FROM employees e
LEFT JOIN employees m ON m.id = e.manager_id
ORDER BY e.id;Ada gets no manager. Ben and Cy get Ada. Di gets Ben. The LEFT JOIN produces a NULL m.name for Ada, and COALESCE replaces it for display.
COALESCE is shorthand for CASE
COALESCE(a, b) is defined as the same thing as this expression:
CASE WHEN a IS NOT NULL THEN a ELSE b ENDThe standard says later arguments are only evaluated when needed. In practice, do not rely on that to guard against errors, because an optimizer may fold constants early. If a fallback expression could raise an error, such as a division, protect it explicitly with NULLIF or a CASE.
The arguments must share a type
All arguments must resolve to one common data type. A fallback that does not fit that type fails or silently converts, depending on the system.
-- Fails in PostgreSQL: 'none' cannot be converted to INTEGER.
SELECT name, COALESCE(manager_id, 'none') FROM employees;
-- Works: convert the number to text first.
SELECT name, COALESCE(CAST(manager_id AS VARCHAR(10)), 'none') AS manager_ref
FROM employees;Some systems, such as MySQL and SQLite, are more lenient and mix types without an error. Do not depend on that. Cast explicitly so the query means the same thing everywhere. MySQL's CAST target for text is CHAR, not VARCHAR.
NULLIF: turning a value into NULL
NULLIF(a, b) returns NULL when a equals b. Otherwise it returns a. It is the same as CASE WHEN a = b THEN NULL ELSE a END.
The common reason to use it is to convert a placeholder value, called a sentinel, into a true NULL. Messy data often uses empty strings where NULL was meant. Set up a small table to see this:
CREATE TABLE contacts (
id INTEGER PRIMARY KEY,
phone VARCHAR(20)
);
INSERT INTO contacts (id, phone) VALUES
(1, '555-0100'),
(2, ''),
(3, NULL);
SELECT id,
NULLIF(phone, '') AS phone_clean
FROM contacts
ORDER BY id;Rows 2 and 3 now both return NULL, and row 1 is unchanged. If phone itself is NULL, phone = '' is UNKNOWN, so NULLIF returns phone, which is NULL. A NULL input never causes an error.
Avoiding division by zero
Dividing by zero raises an error in most systems. Dividing by NULL returns NULL. So NULLIF(divisor, 0) converts a possible error into a NULL result:
CREATE TABLE campaigns (
name VARCHAR(20),
clicks INTEGER,
impressions INTEGER
);
INSERT INTO campaigns (name, clicks, impressions) VALUES
('spring', 10, 200),
('draft', 0, 0);
SELECT name,
clicks * 1.0 / NULLIF(impressions, 0) AS click_rate
FROM campaigns;spring returns 0.05. draft returns NULL instead of failing the whole query. The * 1.0 forces decimal division, because some systems divide two integers as integers.
Combining the two
The two functions work well together. NULLIF normalizes bad placeholders to NULL. COALESCE then supplies one display value for every missing case:
SELECT id,
COALESCE(NULLIF(TRIM(phone), ''), 'no phone') AS phone_display
FROM contacts
ORDER BY id;Row 1 shows 555-0100. Rows 2 and 3 both show no phone. TRIM first removes spaces, so a value of three spaces is also treated as empty. The order matters: NULLIF must run inside COALESCE, because COALESCE only replaces actual NULLs.
Choosing a replacement: it changes the meaning
COALESCE(x, 0) does not just tidy the output. It changes what the data says. A NULL commission means "no commission recorded". A zero commission means "a commission of zero". These can produce different aggregate results, as the earlier chapter on aggregates showed:
SELECT AVG(commission) AS avg_non_null, -- 200.00
AVG(COALESCE(commission, 0)) AS avg_with_zeros -- 100.00
FROM employees;Neither answer is wrong. They answer different questions: the average of commissions that exist, or the average per employee. Decide which one you mean before adding COALESCE inside an aggregate. Applying it only at the final display step, after the aggregate, keeps the calculation honest.
The same applies to sums that must not hide missing data. SUM(commission) returns NULL, not 0, when every input is NULL. Wrapping the outer result, COALESCE(SUM(commission), 0), is the usual way to make an empty group show zero.
Performance: COALESCE in WHERE
Wrapping a column in a function in a WHERE clause usually stops the database from using an ordinary index on that column. Compare:
-- Likely cannot use an index on commission.
SELECT name FROM employees WHERE COALESCE(commission, 0) = 0;
-- Same result, and the column is left alone.
SELECT name FROM employees
WHERE commission = 0 OR commission IS NULL;Both return Ada and Cy. The second form is longer but lets the optimizer use an index on commission. For a small table the difference does not matter. On a large table, check the query plan.
Vendor-specific alternatives
COALESCE and NULLIF are in the SQL standard and work in PostgreSQL, MySQL, SQL Server, Oracle, and SQLite. Each system also has a two-argument shortcut for COALESCE.
| System | Shortcut | Notes |
|---|---|---|
| Oracle | `NVL(a, b)` | Two arguments only |
| MySQL | `IFNULL(a, b)` | Two arguments only |
| SQL Server | `ISNULL(a, b)` | Result takes the data type of `a`, which can truncate `b` |
| SQLite | `IFNULL(a, b)` | Two arguments only |
Prefer COALESCE in portable code. The SQL Server ISNULL type rule is a real trap: ISNULL(short_col, 'a long fallback') cuts the fallback to the length of short_col. COALESCE picks a type that fits all arguments.
Common mistakes
- Putting
COALESCEin aWHEREtest whenIS NULLwould do, which hides indexes and obscures intent. - Replacing NULL with 0 or an empty string and then forgetting that the value is no longer "unknown".
- Using a sentinel like
-1or'N/A'as the replacement and then summing or sorting it as real data. - Writing
COALESCE(a, b)whereaandbhave incompatible types. - Expecting
NULLIF(a, NULL)to do something useful.a = NULLis UNKNOWN, so it always returnsa.
Exercise
Using the employees table, write a query that returns each employee's name and a column called commission_label. The label should be the commission as text when one exists, and the text 'none' when it does not. What does the row for Cy show, and why does casting matter?
Show answer
SELECT name, COALESCE(CAST(commission AS VARCHAR(20)), 'none') AS commission_label FROM employees; Cy shows 'none', because Cy's commission is NULL and COALESCE returns the next argument. The cast matters because COALESCE needs all arguments to share a type. Without it, a strict system such as PostgreSQL rejects 'none' as a NUMERIC value.
Exercise
The campaigns table contains ('spring', 10, 200) and ('draft', 0, 0). Write a query returning each campaign's click_rate as a decimal, showing 0 instead of NULL when impressions is 0. Then explain why this may be a poor choice for reporting.
Show answer
SELECT name, COALESCE(clicks * 1.0 / NULLIF(impressions, 0), 0) AS click_rate FROM campaigns; The result is 0.05 for spring and 0 for draft. It may be a poor choice because a campaign with no impressions has no meaningful rate, yet 0 reads as "everyone ignored it". Leaving NULL, or averaging only rows where impressions > 0, keeps that difference visible.