Concept Flow - NULLIF function behavior
Start NULLIF(a, b)
Compare a and b
Return NULL
End
NULLIF compares two values; if they are equal, it returns NULL, otherwise it returns the first value.
SELECT NULLIF(5, 5) AS result1, NULLIF(5, 3) AS result2;
| Step | Input a | Input b | Condition (a = b)? | Output |
|---|---|---|---|---|
| 1 | 5 | 5 | True | NULL |
| 2 | 5 | 3 | False | 5 |
| 3 | NULL | NULL | UNKNOWN | NULL |
| 4 | NULL | 5 | UNKNOWN | NULL |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | After Step 4 |
|---|---|---|---|---|---|
| a | 5 | 5 | 5 | NULL | NULL |
| b | 5 | 5 | 3 | NULL | 5 |
| Output | N/A | NULL | 5 | NULL | NULL |
NULLIF(a, b) returns NULL if a equals b. Otherwise, it returns a. If both inputs are NULL, it returns NULL. Useful to avoid division by zero or replace equal values with NULL.
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