ISNULL Function
Purpose: Replaces NULL values with a specified replacement value.
Example: Imagine a table named Products with a column Discount that may contain NULL values. To handle these NULL values gracefully in a query, you can use ISNULL to ensure all output values are non-null.
SELECT ProductName, ISNULL(Discount, 0) AS EffectiveDiscount
FROM Products;
NULLIF Function
Purpose: Returns NULL if two given expressions are equal; otherwise, returns the first expression. This is particularly useful for avoiding errors in calculations.
Example: Consider a table named Sales with columns TotalSales and NumberOfTransactions. To avoid division by zero when calculating the average sale per transaction, use NULLIF.
SELECT TotalSales, NumberOfTransactions,
TotalSales / NULLIF(NumberOfTransactions, 0) AS AvgSalePerTransaction
FROM Sales;
COALESCE Function
In modern SQL environments, while ISNULL and NULLIF remain fundamentally the same, there's a broader acceptance and usage of more universally supported functions like COALESCE which is similar to ISNULL but can handle multiple parameters. COALESCE returns the first non-null value in a list of parameters.
SELECT ProductName, COALESCE(Discount, 5) AS EffectiveDiscount
FROM Products;