NULLIF, ISNULL and COALESCE
In SQL Server, NULLIF, ISNULL, and COALESCE are functions used to handle null values in different ways. Here's an explanation of each function:
Here's a detailed explanation of each function with examples:
1-NULLIF:
-
The NULLIF function compares two expressions and returns NULL if they are equal, or the first expression if they are not equal.
-
It is often used when you want to treat a specific value as null.
-
Example: Suppose we have a table called Students with columns Name and Age. If we want to replace occurrences of the name "Unknown" with NULL, we can use NULLIF as follows:
SELECT NULLIF(Name, 'Unknown') AS NewName, Age FROM Students;
This query will return the Name column, but replace "Unknown" with NULL.
2-ISNULL:
-
The ISNULL function replaces NULL values with a specified replacement value.
-
It is commonly used to provide a default value when a column contains NULL.
-
Example: Let's consider a table called Employees with columns Name and Department. If we want to display the department as "Unknown" when it is NULL, we can use ISNULL like this:
SELECT Name, ISNULL(Department, 'Unknown') AS Department FROM Employees;
This query will return the Name and Department columns, replacing NULL values in the Department column with the string 'Unknown'.
3-COALESCE:
-
The COALESCE function returns the first non-null expression from a list of expressions.
-
It is useful when you want to select the first available non-null value from a set of options.
-
Example: Let's consider a table called Products with columns Name, Price, and PromoPrice. If we want to display the promotional price, but fallback to the regular price if the promotional price is NULL, we can use COALESCE like this:
SELECT Name, COALESCE(PromoPrice, Price) AS FinalPrice FROM Products;
This query will return the Name column and a calculated column FinalPrice, which takes the PromoPrice if it's not NULL, or falls back to the Price column if the PromoPrice is NULL.
These examples illustrate the usage of NULLIF, ISNULL, and COALESCE in different scenarios to handle null values or provide default values. Remember that the specific syntax and behavior of these functions may vary slightly depending on the database system you are using.