Introduction
NULLIF helps you avoid errors by returning NULL when two values are the same, making your data cleaner and easier to work with.
NULLIF(value1, value2)
SELECT NULLIF(5, 5);
SELECT NULLIF(5, 3);
SELECT NULLIF('apple', 'apple');
SELECT NULLIF('apple', 'orange');
SELECT product_id, price, NULLIF(price, 0) AS price_or_null FROM products ORDER BY product_id;
NULLIF function return when both its arguments are equal?NULLIF function compares two values and returns NULL if they are equal.NULLIF returns NULL instead of any value.NULLIF in PostgreSQL?NULLIF is a standard SQL function that takes two arguments inside parentheses separated by a comma.NULLIF(value1, value2) uses parentheses and comma correctly.SELECT NULLIF(5, 5) AS result1, NULLIF(7, 5) AS result2;
NULLIF(5, 5) returns NULL.NULLIF(7, 5) returns the first argument, 7.SELECT NULLIF(10 10) AS result;
NULLIF must be separated by a comma.NULLIF(10 10) missing a comma between 10 and 10.SELECT value / divisor FROM numbers;
NULLIF to prevent errors when divisor is zero?NULLIF(divisor, 0) returns NULL if divisor is zero, preventing division by zero error.value / NULLIF(divisor, 0). SELECT NULLIF(value, 0) / divisor FROM numbers; replaces value, not divisor. SELECT value / divisor WHERE divisor != 0; filters rows but does not use NULLIF. SELECT value / divisor NULLIF divisor, 0 FROM numbers; has syntax error.Pass the test and this pattern moves unknown