NULLIF is a scalar conditional expression defined in the SQL standard that compares two expressions. If expression1 equals expression2 after type coercion, the function returns NULL; otherwise it returns expression1 unchanged. NULLIF is often used to prevent errors such as divide-by-zero or to convert specific sentinel values (for example 0 or -1) into NULLs so they can be handled uniformly by aggregate functions or COALESCE.Because NULLIF only evaluates its two arguments once, it is more efficient and concise than equivalent CASE statements like CASE WHEN expr1 = expr2 THEN NULL ELSE expr1 END. The data type of the result is the same as expression1 (after implicit casting if needed). Both arguments are evaluated before comparison, so avoid side-effects in their evaluation. NULLIF follows normal NULL comparison semantics: if either argument is NULL, the comparison returns UNKNOWN, and the function therefore returns expression1.
expression1
(any comparable expression) - The value that will be returned if it is not equal to expression2.expression2
(any comparable expression) - The value to compare against expression1 to determine whether NULL should be returned.COALESCE, CASE, IS NULL, IFNULL, DECODE
SQL:1999 standard
It returns the value of the first expression unchanged.
NULLIF turns certain values into NULL, while COALESCE turns NULL into the first non-NULL value in its argument list.
Yes. Wrapping the divisor with NULLIF(divisor, 0) converts zero to NULL, causing the result of the division to become NULL instead of raising an error.
Absolutely. You can compare any data types that are comparable in your SQL dialect, including VARCHAR, DATE, and numeric types.