ISNULL vs COALESCE in SQL Server

In our T-SQL programming, we mostly use ISNULL function to replace the null value of a column with another value. The same can be achieved using COALESCE function too. In this blog post, we are going to see a significant difference between NULL and COALESCE functions. We are going to discuss about the implicit conversion used by ISNULL and COALESCE functions.

What is COALESCE:

Evaluates the arguments in order and returns the current value of the first expression that initially does not evaluate to NULL.

Thus COALESCE gives a substitute value for NULL values from the given list of columns. It always returns the first NON-NULL from the list.

Syntax : – COALESCE ( expression [ ,…n ] )

COALESCE vs ISNULL

When we use ISNULL to get the substitute value for any NULL value it implicitly type casts the substitute as per the checked column or value type. But the COALESCE does not.

Example:

DECLARE @ch_ToCheck CHAR(1)
SELECT ISNULL(@ch_ToCheck, 'XYZ')
GO

Now from above query we are expecting to get ‘XYZ’ as the value, but it will return ‘X’ and not ‘XYZ’. Because the type of the checked Value is CHAR(1), it will implicitly cast the substitute as CHAR(1).

Now try the same with COALESCE:

DECLARE @ch_ToCheck CHAR(1)
SELECT COALESCE(@ch_ToCheck, 'XYZ')
GO

And you will get ‘XYZ’.

Conclusion

With the help of above example, i just tried to explain the type casting feature of ISNULLs with COALESCE and I am not saying that you should completely avoid the use of ISNULL . Just keep in your mind this significant difference.

About Gopal Krishna Ranjan

I am Gopal Krishna Ranjan, having 8 years of industry experience in Software development. I have a head down experience in Database, Data Warehouse, Big Data and cloud technologies and have implemented end to end Database, Data Warehouse, Big Data and Cloud Solutions.
I have extensively worked on SQL Server, Python, Hadoop, Hive, Spark, Azure, Machine Learning, and MSBI (SSAS, SSIS, and SSRS). I also have good experience in windows and web application development using ASP.Net and C#.