Sub topic 5
COALESCE and NULLIF
Assume you know basic SELECT ... FROM ... WHERE queries, common column types, and aggregate functions such as COUNT and SUM. This chapter focuses on two scalar functions that make expressions safer when values are missing or exceptional.
Why NULL needs special handling
NULL means “unknown” or “missing.” It is not the same as zero, an empty string, or FALSE.
Most arithmetic with NULL produces NULL:
SELECT salary + commission AS total_pay
FROM employees;If an employee has no commission, the result for that employee is NULL. SQL cannot know whether the missing commission should count as zero.
Comparisons with NULL also do not produce TRUE or FALSE. They produce an unknown result:
SELECT *
FROM employees
WHERE commission = NULL;This does not find missing commissions. Use IS NULL or IS NOT NULL for direct tests.
Replacing missing values with COALESCE
COALESCE returns the first argument that is not NULL. It accepts two or more arguments.
SELECT first_name,
salary + COALESCE(commission, 0) AS total_pay
FROM employees;For each row, SQL checks commission:
- If
commissionhas a value,COALESCEreturns that value. - If
commissionisNULL, it returns0. - The addition therefore produces a numeric result instead of
NULL.
You can provide more than one fallback:
SELECT COALESCE(nickname, preferred_name, first_name, 'Unknown') AS display_name
FROM customers;SQL returns the first non-NULL value from left to right. If every argument is NULL, COALESCE returns NULL.
| Expression | Result |
|---|---|
| `COALESCE(25, 0)` | `25` |
| `COALESCE(NULL, 0)` | `0` |
| `COALESCE(NULL, NULL, 'Unknown')` | `'Unknown'` |
Avoiding division by zero with NULLIF
NULLIF compares two expressions. It returns NULL when they are equal; otherwise, it returns its first expression.
SELECT total_revenue / NULLIF(order_count, 0) AS average_order_value
FROM sales_summary;When order_count is zero, NULLIF(order_count, 0) returns NULL. Dividing by NULL produces NULL instead of raising a division-by-zero error.
When order_count is not zero, NULLIF returns the count unchanged.
You can combine both functions when you need a display value for the safe result:
SELECT sales_rep_id,
COALESCE(total_revenue / NULLIF(order_count, 0), 0)
AS average_order_value
FROM sales_summary;This query has two separate decisions:
NULLIFturns an invalid zero denominator intoNULL.COALESCEchanges the resultingNULLinto0.
That final replacement is a reporting choice. A NULL average can mean “there were no orders,” while zero can suggest that the average was measured and happened to be zero.
Combining functions in aggregates
COALESCE is useful inside aggregate expressions when missing values should contribute a known amount.
SELECT department_id,
SUM(COALESCE(commission, 0)) AS total_commission
FROM employees
GROUP BY department_id;SUM ignores NULL values, but it can return NULL when every value in a group is NULL. To guarantee a result of zero for an entirely empty set or all-NULL values, apply COALESCE around the aggregate:
SELECT department_id,
COALESCE(SUM(commission), 0) AS total_commission
FROM employees
GROUP BY department_id;The placement changes the meaning slightly. Choose the form that matches the data rule you need.
Common errors
- Use
IS NULL, not= NULL, to test for missing values. - Do not assume every database treats text and numbers as interchangeable in
COALESCE. - Check the result type when fallback values have different types.
- Remember that
NULLIF(value, value)always returnsNULL. - Decide whether an unknown result should remain
NULLor become a reporting value such as zero.
Exercise
Write a query that calculates revenue_per_customer from revenue and customer_count, returns NULL when customer_count is zero, and uses the alias revenue_per_customer.
Show answer
SELECT revenue / NULLIF(customercount, 0) AS revenuepercustomer FROM salessummary;