Null Functions in SQL Server
In SQL Server, there are several functions available to handle NULL values. These functions allow you to perform operations on columns or expressions that may contain NULL values and handle them appropriately. Here are some commonly used NULL functions in SQL Server:
1- ISNULL(): The ISNULL() function replaces a NULL value with a specified value. It takes two arguments: the expression to be evaluated and the value to be returned if the expression is NULL.
SELECT ISNULL(column_name, replacement_value) AS new_column_name
FROM table_name;
2- COALESCE(): The COALESCE() function returns the first non-NULL expression from a list of expressions. It takes multiple arguments and evaluates them in order until a non-NULL value is found.
SELECT COALESCE(column_name1, column_name2, column_name3) AS new_column_name
FROM table_name;
3- NULLIF(): The NULLIF() function compares two expressions and returns NULL if they are equal; otherwise, it returns the first expression. It is often used to handle division by zero or when you want to replace a specific value with NULL.
SELECT NULLIF(expression1, expression2) AS new_column_name
FROM table_name;
4- ISNULL() vs COALESCE(): The ISNULL() function works with only two arguments and returns the replacement value if the expression is NULL. In contrast, the COALESCE() function can handle multiple arguments and returns the first non-NULL value from the list of expressions.
5- CASE statement: The CASE statement allows you to perform conditional logic and handle NULL values. You can use it to define different actions or values based on the presence or absence of NULL values.
SELECT column_name,
CASE
WHEN column_name IS NULL THEN 'Null value'
ELSE 'Non-null value'
END AS new_column_name
FROM table_name;
These NULL functions in SQL Server provide flexibility in handling NULL values during data retrieval and manipulation. They help you to replace, compare, or handle NULL values appropriately based on your specific requirements.