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.
- Category
- Conditional
- Returns
type of the first argument- In this category
- 2 of 43
Syntax
NULLIF(value, value_to_null_out)
Engine support
| Engine | Support | Notes |
|---|---|---|
| SQL Server | Yes | Supported under this name. |
| PostgreSQL | Yes | Supported under this name. |
| MySQL | Yes | Supported under this name. |
| SQLite | Yes | Supported under this name. |
| Oracle | Yes | Supported under this name. |
Examples
Any engine
SELECT total / NULLIF(order_count, 0) AS avg_order FROM summaries;
Any engine
SELECT NULLIF(TRIM(alias), '') AS clean_alias FROM users;
Good to know
- 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.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
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.