Wednesday, August 19, 2020

What is COALESCE(), IFNULL, ISNULL in sql server ?

 

SQL Server COALESCE() Function


Return the first non-null value in a list:

SELECT COALESCE(NULLNULLNULL'Vijay'NULL'Kumar');

Output : Vijay.

MySQL COALESCE vs. IFNULL

The IFNULL function takes two arguments and returns the first argument if it is not NULL, otherwise, it returns the second argument.

The IFNULL function works great with two arguments whereas the COALESCE function works with n arguments. In case the number of arguments is two, both functions are the same.

P_IdProductNameUnitPriceUnitsInStockUnitsOnOrder
1Jarlsberg10.451615
2Mascarpone32.5623 
3Gorgonzola15.67920

Suppose that the "UnitsOnOrder" column is optional, and may contain NULL values.

Look at the following SELECT statement:

SELECT ProductName, UnitPrice * (UnitsInStock + UnitsOnOrder)
FROM Products;

In the example above, if any of the "UnitsOnOrder" values are NULL, the result will be NULL.


Solutions

MySQL

The MySQL IFNULL() function lets you return an alternative value if an expression is NULL:

SELECT ProductName, UnitPrice * (UnitsInStock + IFNULL(UnitsOnOrder, 0))
FROM Products;

or we can use the COALESCE() function, like this:

SELECT ProductName, UnitPrice * (UnitsInStock + COALESCE(UnitsOnOrder, 0))
FROM Products;

SQL Server

The SQL Server ISNULL() function lets you return an alternative value when an expression is NULL:

SELECT ProductName, UnitPrice * (UnitsInStock + ISNULL(UnitsOnOrder, 0))
FROM Products;




No comments:

Post a Comment