// conditional reference

SQL NULLIF function

Returns NULL when its two arguments are equal, and the first argument otherwise. Where COALESCE replaces NULLs with a value, NULLIF turns a placeholder value back into NULL.

類別
條件
Returns
type of the first argument
In this category
2 of 43

語法

NULLIF(value, value_to_null_out)

引擎支援

引擎Support備註
SQL Server 是 Supported under this name.
PostgreSQL 是 Supported under this name.
MySQL 是 Supported under this name.
SQLite 是 Supported under this name.
Oracle 是 Supported under this name.

範例

Any engine

SELECT total / NULLIF(order_count, 0) AS avg_order
FROM summaries;

Any engine

SELECT NULLIF(TRIM(alias), '') AS clean_alias FROM users;

小知識

  • It is shorthand for CASE WHEN a = b THEN NULL ELSE a END, which is why it takes exactly two arguments.
  • The usual division guard: total / NULLIF(count, 0) returns NULL instead of a divide-by-zero error.
  • Watch types: on SQL Server NULLIF('abc', 0) fails converting 'abc' to int, because the comparison uses the higher-precedence type. Keep both arguments the same type.

Questions about NULLIF

What is NULLIF used for?

Turning sentinels into NULL: blank strings, zero counts, legacy -1 flags. Most often seen as the divide-by-zero guard total / NULLIF(n, 0).

Does NULLIF compare NULL to NULL?

No. NULLIF(NULL, x) returns NULL because the first argument is NULL. NULLIF(x, NULL) returns x, because x = NULL is never true, so the values are never treated as equal.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.