T-SQL Tutorial

NULLIF


The NULLIF expression in SQL Server is a useful function that allows you to compare two expressions and return a null value if they are equal. It helps you handle situations where you want to avoid division by zero errors or when you need to substitute a specific value with NULL.


Syntax

The syntax for the NULLIF expression is as follows:

NULLIF(expression1, expression2)

The expression1 and expression2 are the two values or columns you want to compare. If expression1 and expression2 are equal, the NULLIF function returns a null value. Otherwise, it returns the value of expression1.


Examples

Here are a few examples to illustrate how the NULLIF expression works:

1. Avoiding division by zero errors:

SELECT column1 / NULLIF(column2, 0) AS result
FROM table;

In this example, if the value of column2 is zero, the NULLIF function will return a null value, preventing the division by zero error. Otherwise, it will perform the division operation as usual.

2. Replacing a specific value with NULL:

SELECT NULLIF(column1, 'N/A') AS result
FROM table;

In this case, if the value of column1 is 'N/A', the NULLIF function will return a null value. Otherwise, it will return the original value of column1.

3. Handling NULL values:

SELECT NULLIF(column1, NULL) AS result
FROM table;

Here, if the value of column1 is NULL, the NULLIF function will return a null value. Otherwise, it will return the original value of column1.

It's important to note that the NULLIF expression is evaluated before any other expressions in the SELECT statement. Therefore, if you use the NULLIF function within a calculation or as a condition in a WHERE clause, the comparison will be made and the null value will be generated before other operations take place.

In conclusion, the NULLIF expression in SQL Server provides a convenient way to handle comparisons and substitutions in SQL queries. It is particularly useful in scenarios where you need to handle division by zero errors or replace specific values with NULL.