PostgreSQL 18 reference · Conditional and Type Expressions

PostgreSQL NULLIF() Function

Return NULL if two values are equal, otherwise the first one. Commonly used to avoid division by zero.

PostgreSQL 18

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

NULLIF(value1, value2)

Parameters

ParameterDescription
value1 The value.
value2 The value that should become NULL.

Return value

NULL or value1.

Examples

Equal values become NULL
SELECT nullif(5, 5) AS same, nullif(5, 3) AS different;

Output

 same | different
------+-----------
 NULL |         5
(1 row)

Run this on your computer — see “Get Started” for setup.

Avoid dividing by zero
SELECT name, round(100.0 / nullif(stock, 0), 2) AS pct_per_unit
FROM products
WHERE product_id IN (2, 3);

Output

           name           | pct_per_unit
--------------------------+--------------
 Clean Code               |         6.67
 The Pragmatic Programmer |         NULL
(2 rows)

Run this on your computer — see “Get Started” for setup.

In other languages

Was this page helpful?