CodeOath
← All posts
SQL70 min total · 18 parts

SQL Fundamentals: Joins, NULL, Aggregate Functions, and Subqueries

Contents — Part 8 of 18: COALESCE, NULLIF, and Handling NULL in Expressions
Part 8 of 18 · ~1 min

COALESCE, NULLIF, and Handling NULL in Expressions

COALESCE(a, b, c, ...) returns the first argument that isn't NULL — the standard way to substitute a default value when a calculation or display genuinely does want a fallback instead of "unknown":

SELECT name, COALESCE(salary, 0) AS salary_or_zero FROM Employees;
-- Dave now shows 0 instead of NULL, for display purposes

Be careful applying this inside a calculation rather than just for display — COALESCE(salary, 0) for an average deliberately changes the meaning of the average (it now treats missing data as "earns nothing," which is a real, different question from "what do employees with known salaries earn"). Decide which question you're actually answering before reaching for COALESCE inside AVG().

NULLIF(a, b) is the inverse idea — it returns NULL if the two arguments are equal, otherwise returns the first one. It's most commonly used to avoid a division-by-zero error by turning a zero divisor into NULL (which propagates cleanly through arithmetic rather than throwing):

SELECT name, salary / NULLIF(0, 0) AS example FROM Employees LIMIT 1;
-- NULLIF(0, 0) is NULL, so the division becomes salary / NULL = NULL, not an error