NULLIF: Convert a matching value to NULL
Core idea
NULLIF(a, b) returns NULL when a and b compare equal; otherwise it returns the first value (subject to type resolution). It is useful for converting known sentinel values or preventing a zero denominator.
Minimal example
SELECT NULLIF(5, 5), NULLIF(5, 0);Expected SQLite rows:
NULL | 5How it works
Use numerator / NULLIF(denominator, 0) when a missing result is the intended meaning for division by zero. The score example divides 100 by each score: the zero and missing scores yield NULL. SQLite already returns NULL for division by zero, whereas PostgreSQL normally raises an error for integer division by zero. The explicit expression communicates the intended policy.
Practical example
SELECT id, 100 / NULLIF(score, 0) AS ratio FROM sort_scores ORDER BY id;Expected SQLite rows:
1 | 102 | NULL3 | NULL4 | NULLCommon mistake and practice
Do not silently treat every zero as missing. NULLIF only changes the expression result, not the table. Practice: use NULLIF to treat a blank text value as missing and test both an empty string and a nonempty string.