COALESCE, NULLIF & CAST in SQL
Defaults, guards, and type bridges
COALESCE returns the first non-NULL — default substitution without overwriting storage. NULLIF(a,b) returns NULL when equal — division guards and sentinel collapsing. CAST(x AS NUMERIC) or x::NUMERIC bridges types (INT→DECIMAL before division). IS DISTINCT FROM is the null-safe <> standard. All nest and compose.
COALESCE defaults
First non-NULL wins — display/math defaults without rewriting storage.
NULLIF guards
NULLIF(x,0) turns zero-division into NULL; collapses sentinels.
CAST bridges
CAST/:: converts INT→DECIMAL before division; explicit over implicit conversion.
Compare NULL-safe
IS DISTINCT FROM is null-safe <>; = NULL never matches — IS NULL tests.
1SELECT name, COALESCE(bonus, 0) AS bonus, salary / 12.0 AS monthly FROM employees LIMIT 3;
| name | bonus | monthly |
|---|---|---|
| Alice | 5000 | 7083.33 |
| Bob | 0 | 4333.33 |
| Cynthia | 0 | 7583.33 |
Bob and Cynthia have NULL bonuses — COALESCE shows 0 without changing storage. Monthly uses decimal division. COUNT(*) stays 6 while COUNT(bonus) is 3 — aggregates skip NULLs.
Bonus defaults + decimal mean
NULLs shown as 0; means kept decimal.
1SELECT name, COALESCE(bonus, 0) AS bonus, salary / 12.0 AS monthly FROM employees LIMIT 2;
| name | bonus | monthly |
|---|---|---|
| Alice | 5000 | 7083.33 |
| Bob | 0 | 4333.33 |
Guard + cast + safe compare
Three null/type tools in one row.
1SELECT salary / NULLIF(months, 0) AS rate, CAST(salary AS DECIMAL) / 12 AS exact FROM employees LIMIT 1;
| rate | exact |
|---|---|
| null | 7083.33 |
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Take the queries you just visualized and see the data structures that power real databases.