SQL Server NULLIF() Function

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



NULLIF(): Definition and Usage

NULLIF() is handy for situations where you want to treat equality between two expressions as a special case, resulting in a NULL value. This can be very useful in various data manipulation tasks and conditional logic within your SQL queries. It's a concise way to handle cases where you want to treat equality as a specific condition resulting in a null value.

Syntax

Syntax

NULLIF(expr1, expr2)
      

Parameter Values

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

Examples

Comparing Identical Numeric Values

This example shows that when both expressions are equal, NULLIF() returns NULL.

Syntax

SELECT NULLIF(25, 25);
      
Output

NULL
      

Comparing Identical String Values

Similar to the above, but with strings.

Syntax

SELECT NULLIF('Hello', 'Hello');
      
Output

NULL
      

Comparing Different Values

When the expressions are different, the first expression is returned.

Syntax

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

Hello
      

Comparing Identical Date Strings

Demonstrates the behavior with date strings.

Syntax

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

NULL