sqlcmd.net validated sql reference
intermediate null-handling MySQL MariaDB SQL Server PostgreSQL SQLite

Return NULL When Two Values Are Equal With NULLIF

Use `NULLIF` to convert a specific value to `NULL`, most commonly to prevent division-by-zero errors.

Docker-validated Not currently validation-green

Divide values safely by converting a zero divisor to NULL

For alpha, NULLIF(0, 0) returns NULL, so 100 / NULL yields NULL instead of a division-by-zero error. For beta and gamma, the divisor is non-zero so NULLIF returns it unchanged, and normal division proceeds.

Rows loaded before the example query runs.
Setup
CREATE TABLE metrics (id INT, label VARCHAR(50), VALUE INT, divisor INT);

INSERT INTO
  metrics (id, label, VALUE, divisor)
VALUES
  (1, 'alpha', 100, 0),
  (2, 'beta', 200, 4),
  (3, 'gamma', 150, 3);
Shared across supported engines.
SQL
SELECT
  label,
  VALUE,
  divisor,
  VALUE / NULLIF(divisor, 0) AS RESULT
FROM
  metrics
ORDER BY
  id;
Returned rows for the shared example.
labelvaluedivisorresult
alpha1000NULL
beta200450
gamma150350

Output is identical across all engines.

Where this command helps.

  • preventing division-by-zero errors in computed columns
  • converting a sentinel value to NULL for consistent null handling

What the command is doing.

NULLIF(x, y) returns NULL if x equals y, otherwise it returns x. The most common use is value / NULLIF(denominator, 0): when the denominator is zero, NULLIF turns it into NULL, and dividing by NULL returns NULL instead of raising a division-by-zero error.