Sub topic 5
COALESCE and NULLIF
This chapter assumes you can write basic SELECT ... FROM ... WHERE queries and know the common column types. It also assumes you know that NULL means "unknown or missing", and that arithmetic on NULL returns NULL. The previous chapter covered those rules. This chapter covers the two standard functions for controlling them: COALESCE and NULLIF.
The two functions are opposites. COALESCE turns a NULL into a real value. NULLIF turns a real value into a NULL. Used together, they let you clean up data inside an expression without changing the table.
Sample data
The examples use two small tables. The statements run unchanged on PostgreSQL and SQLite.
CREATE TABLE employees (
employee_id INTEGER,
first_name VARCHAR(50),
salary INTEGER,
commission INTEGER,
nickname VARCHAR(50)
);
INSERT INTO employees VALUES
(1, 'Ana', 60000, 5000, 'A'),
(2, 'Ben', 50000, NULL, ''),
(3, 'Chloe', 80000, NULL, NULL);
CREATE TABLE sales_summary (
region VARCHAR(20),
total_revenue NUMERIC(10,2),
order_count INTEGER
);
INSERT INTO sales_summary VALUES
('North', 1200.00, 4),
('South', 0.00, 0);Ben has a commission of NULL (unknown or not applicable) and a nickname of '' (an empty string). Chloe has NULL for both. These are different situations, and the two functions handle them differently.
COALESCE: the first non-NULL value
COALESCE(a, b, c, ...) evaluates its arguments from left to right and returns the first one that is not NULL. If every argument is NULL, it returns NULL.
The most common use is to substitute a default so that NULL does not spread through arithmetic:
SELECT first_name,
salary + COALESCE(commission, 0) AS total_pay
FROM employees;| first_name | total_pay |
|---|---|
| Ana | 65000 |
| Ben | 50000 |
| Chloe | 80000 |
Without COALESCE, Ben and Chloe would have NULL for total_pay, because 50000 + NULL is NULL.
COALESCE accepts more than two arguments, which makes it useful for fallback chains. This query picks a display name from the nickname, then the first name, then a literal:
SELECT employee_id,
COALESCE(nickname, first_name, 'unknown') AS display_name
FROM employees;Why COALESCE is not the same as a default value in the table
COALESCE changes only the result of the query. The stored data stays NULL. This matters when you aggregate, because aggregate functions skip NULL inputs:
SELECT AVG(commission) AS avg_of_known,
AVG(COALESCE(commission, 0)) AS avg_all_employees
FROM employees;AVG(commission) returns 5000, because only Ana's value counts. AVG(COALESCE(commission, 0)) returns about 1666.67, because all three employees count and two of them contribute 0. Neither answer is wrong, but they answer different questions. Before you add COALESCE(x, 0), decide whether "missing" really means "zero". A missing temperature reading is not a reading of 0 degrees.
Types and argument rules
All arguments to COALESCE must be of compatible types, and the result has a single type that all branches are converted to. This follows the same rule as CASE, covered later in this tutorial. Mixing incompatible types fails in strict databases:
-- Fails in PostgreSQL: integer and text are not compatible
SELECT COALESCE(commission, 'none') FROM employees;
-- Works: convert the number to text first
SELECT COALESCE(CAST(commission AS VARCHAR(20)), 'none') AS commission_text
FROM employees;COALESCE also generally does not evaluate arguments after the first non-NULL one. The standard allows this short-circuiting, and the rest of the arguments are not needed once an earlier one has a value. Do not rely on side effects in later arguments.
NULLIF: turning a value into NULL
NULLIF(a, b) returns NULL if a = b, and returns a otherwise. It is equivalent to this CASE expression, which later chapters cover:
CASE WHEN a = b THEN NULL ELSE a ENDAvoiding division by zero
Dividing by zero raises an error in PostgreSQL and SQL Server and aborts the whole query. NULLIF converts the zero divisor to NULL, and dividing by NULL yields NULL:
SELECT region,
total_revenue / NULLIF(order_count, 0) AS avg_order_value
FROM sales_summary;| region | avg_order_value |
|---|---|
| North | 300.00 |
| South | NULL |
South has no orders, so its average order value is undefined. NULL is an honest answer for that. If the report needs a number, wrap the whole expression:
SELECT region,
COALESCE(total_revenue / NULLIF(order_count, 0), 0) AS avg_order_value
FROM sales_summary;Read nested calls from the inside out. NULLIF guards the divisor, the division runs, and COALESCE replaces the final NULL. Place COALESCE around the whole division, not around the divisor. COALESCE(order_count, 0) would only replace a NULL count with 0 and would still divide by zero.
Integer division
If both operands are integers, many databases (PostgreSQL, SQL Server) truncate the result. 7 / NULLIF(2, 0) gives 3, not 3.5. If you need fractions, make one side a decimal, for example CAST(total AS NUMERIC(12,2)) / NULLIF(n, 0).
Combining the two: treat sentinel values as missing
Real data often uses placeholders such as empty strings, 0, or 'N/A' to mean "no value". NULLIF converts a placeholder into a real NULL, and COALESCE then supplies the replacement you want. The pair works as a cleanup step:
SELECT employee_id,
COALESCE(NULLIF(nickname, ''), first_name) AS display_name
FROM employees;| employee_id | display_name |
|---|---|
| 1 | A |
| 2 | Ben |
| 3 | Chloe |
Ben's empty-string nickname is not NULL, so a plain COALESCE(nickname, first_name) would return the empty string for him. NULLIF(nickname, '') fixes that by converting '' to NULL first.
Edge cases to know
- NULL as the second argument of NULLIF.
NULLIF(a, NULL)always returnsa, becausea = NULLis never true.NULLIFcannot be used to test forNULL. - NULL as the first argument of NULLIF.
NULLIF(NULL, 0)returnsNULL. This is harmless. - The first argument is evaluated twice in spirit.
NULLIF(expr, 0)is defined as theCASEform above, so some databases evaluateexprmore than once. This matters only for non-deterministic expressions such asRANDOM(), which can produce unexpected results. - COALESCE in WHERE can block index use. A filter like
WHERE COALESCE(commission, 0) = 0wraps the column in a function, which often prevents the database from using an index oncommission. The equivalentWHERE commission IS NULL OR commission = 0is usually easier for the optimizer to handle. - A literal NULL-only call. Some databases reject
COALESCE(NULL, NULL)because they cannot infer a type for the result. Add a cast, such asCAST(NULL AS INTEGER), if you need this.
Dialect differences
COALESCE and NULLIF are part of standard SQL and work in PostgreSQL, MySQL, SQL Server, Oracle, and SQLite. Most databases also offer a shorter, non-standard function that takes exactly two arguments:
| Database | Two-argument alternative | Notes |
|---|---|---|
| SQL Server | `ISNULL(a, b)` | Result takes the type of `a`, so it can truncate `b`. |
| Oracle | `NVL(a, b)` | Oracle treats an empty string as `NULL`, so `NULLIF(x, '')` is unnecessary there. |
| MySQL | `IFNULL(a, b)` | Also supports `COALESCE`. |
| SQLite | `IFNULL(a, b)` | Also supports `COALESCE`. |
Prefer COALESCE in code you want to move between databases. Use the vendor functions only when you have a reason.
Summary of behavior
| Expression | Result |
|---|---|
| `COALESCE(NULL, 5)` | 5 |
| `COALESCE(3, 5)` | 3 |
| `COALESCE(NULL, NULL)` | NULL (or a type error in some databases) |
| `NULLIF(5, 5)` | NULL |
| `NULLIF(5, 0)` | 5 |
| `NULLIF(5, NULL)` | 5 |
Exercise
The table employees has a column bonus that is NULL for some rows. A colleague writes SELECT AVG(COALESCE(bonus, 0)) FROM employees and a second colleague writes SELECT AVG(bonus) FROM employees. Why do the two queries return different numbers, and when is each one the right choice?
Show answer
AVG ignores NULL values, so AVG(bonus) averages only the employees who have a bonus. AVG(COALESCE(bonus, 0)) turns every NULL into 0, so every employee counts and the average is lower. Use AVG(bonus) when NULL means "no bonus data or not eligible" and you want the average among those who have one. Use the COALESCE version when NULL really means "received no bonus" and you want the average across all employees.
Exercise
A table products has the columns name, unitssold, and returns. Write a query that returns name and the return rate returns / unitssold as returnrate. Products with unitssold = 0 must show 0 instead of causing an error or NULL. Assume returns and units_sold are DECIMAL columns.
Show answer
SELECT name, COALESCE(returns / NULLIF(unitssold, 0), 0) AS returnrate FROM products; NULLIF(units_sold, 0) turns a zero divisor into NULL, so the division returns NULL instead of failing. COALESCE then replaces that NULL with 0. If the columns were integers, you would also need a cast to avoid truncating the division.