nullif(value1, value2) — Return NULL when the two values are equal
Last updated: 2026-11-04
nullif(value1, value2) — Return NULL when the two values are equal
nullif(a, b) returns NULL when a and b are equal, and otherwise returns a unchanged. Its classic use is guarding against division by zero: wrapping a possibly-zero divisor in nullif(x, 0) makes the division yield NULL instead of raising an error.
| Kind | function |
|---|---|
| Example Language | SQL |
📝 Syntax
nullif(value1 anycompatible, value2 anycompatible) → anycompatible
⚙️ Parameters
| value1 anycompatible | The value that is returned when the two differ. Any type, as long as it is compatible with value2. |
|---|---|
| value2 anycompatible | The value compared against; the result is NULL when it equals value1. |
Returns:anycompatible — NULL when the values are equal, otherwise value1 itself.
▶ Example
Runs real PostgreSQL 18 right in your browser (PGlite WASM, nothing to install). Press ▶ Run and the result appears in the panel below.
Output:
id | label | per_failure | diff_from_baseline
----+---------+-------------+--------------------
1 | batch-a | |
2 | batch-b | 4 |
3 | batch-c | 1 |
(3 rows)
📌 Key Points
- nullif() returns NULL only when the two values are equal; otherwise value1 comes back unchanged.
- Guard a division with nullif(x, 0): a zero divisor turns the result into NULL instead of an error.
- The result is NULL whenever either value is NULL.
💡 Related Cases
More case studies coming soon.
📚 Related Reference
❓ FAQ
QIs nullif(x, 0) the same as CASE WHEN x = 0 THEN NULL ELSE x END?
AThe semantics match, but nullif() is shorter and the planner recognises it, so the expression is not evaluated twice.