Thursday, September 16, 2010

SQL SERVER - ISNULL() vs COALESCE()

Here is the Differences between ISNULL() and COALESCE()

ISNULL() is non-standard and provides less functionality.
COALESCE() is ANSI standard. and is more maintainable, more functional code

ISNULL() Replaces NULL with the specified replacement value
COALESCE() returns first non null value among a list of arguements

ISNULL() uses two arguements only
COALESCE() can use any number of arguements

ISNULL()  returns the same data type as of the first arguement.
COALESCE() is not guaranteed to retrun the same data type as of its first arguement.

Let us see this through an example. At first, Let us declare a variable @str of data type varchar(3). @Str will contain NULL value as we didn't assigned any value to it. Now,

ISNULL(@Str,'ABCDEFGHIJ') retruns 'ABC' , the first three characters of the replacement value as @Str is of datatype Varchar(3).

Where as COALESCE(@Str,'ABCDEFGHIJ') retruns the full string as it does not depend on the  data type of the first arguement.

Declare @str Varchar(3)
Select ISNULL(@STR,'ABCDEFGHIJ') 'ISNULL VALUE', COALESCE(@STR,'ABCDEFGHIJ')  'COALESCE VALUE'

Output :

image

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.