MySQL NULLIF() Function

The NULLIF() function in MySQL compares two expressions. If they are equal, it returns NULL; otherwise, it returns the first expression.



NULLIF(): Definition and Usage

This function is handy for handling situations where you want to treat equality between two expressions as a special case, often resulting in a NULL value. This can be useful in various data manipulation tasks and conditional logic within your SQL queries.

Syntax

Syntax

NULLIF(expr1, expr2)
      

Parameter Values

Parameter Description
expr1, expr2 The two expressions to compare. Both are required.

Examples

Comparing Identical Values

In this case, since both expressions are equal (25 and 25), the function returns NULL.

Syntax

SELECT NULLIF(25, 25);
      
Output

NULL
      

Comparing Different Values (Numeric and String)

Here, the expressions are different, so the first expression (25) is returned.

Syntax

SELECT NULLIF(25, "Hello");
      
Output

25
      

Comparing Different String Values

Another example with different string values.

Syntax

SELECT NULLIF("Hello", "world");
      
Output

Hello
      

Comparing Identical String Values (Date format)

Comparing identical string values representing a date.

Syntax

SELECT NULLIF("2017-08-25", "2017-08-25");
      
Output

NULL