Every day I receive emails from specialist interest groups (Mostly SQL Server) with tips, tricks and articles. One of todays emails mentioned a gotcha with the ISNULL function. I read the rather long winded, slightly repetitive and difficult to follow article, as it contained a very valid point that has been asked of me by past clients. I thought I would give my somewhat shorter answer here.
“Why use the oddly named ‘COALESCE’ function when ‘ISNULL’ does the same thing and is so much more obvious in meaning when reading the code?”
Consider the following example…
declare @a varchar(100)
declare @b varchar(10)
ISNULL returns ‘1234567890’
COALESCE returns ‘123456789012345678901234567890123456789012
This is because ISNULL takes the return type from the first argument yet COALESCE returns the data type of expression with the highest data type precedence.
There are other differences between the funtions too such as ISNULL can only have two arguments whereas COALESCE can have several.
It is an interesting gotcha though as if the result is to be displayed or used in an insert to another table then IsNull can return a tructated result.
Its only fair that I include the original article so here it is…