Coalesce function accepts "n" number of arguments and returns the first non-null expression of the arguments. If all the arguments are null then it returns null.
Syntax
- select coalesce(p1, p2, p3.....n)
- select coalesce(null, 1)
- select coalesce(null, null, 1)
- select coalesce(null, null, 1, null)
- select coalesce(1, 2)

Look at the output, we are getting value as "1" in each output because in all the select statements "1" is first non-null value in the arguments.
NOTE: At least one of the null values must be a typed NULL.
- select coalesce(null, null)

In the above select statement we are passing NULL as value in all arguments and NULL are not typed, so we are getting the error.
Now, let's try with NULL values as typed
- declare @i int
- select coalesce(null, @i)

In this example, it worked fine without any error because values of the argument are still NULL but at least one of them is typed.
Coalesce can be used in place of the following case expression:
- case when expression1 is not null then expression1
- when expression1 is not null then expression1
- ...
- when expressionN is not null then expressionN
- end

Sandeep MittalPosted Nov 14, 2015, 12:44 AM
Thanks everyone...
Harshad PansuriyaPosted Nov 13, 2015, 10:59 PM
Nice one
Banketeshvar NarayanPosted Nov 13, 2015, 10:40 AM
nice
Santhakumar MunuswamyPosted Nov 13, 2015, 10:00 AM
Good one
Humayun Kabir MamunPosted Nov 13, 2015, 1:05 AM
Nice...
Anish AnsariPosted Nov 12, 2015, 8:38 AM
Nice one Sir
Sibeesh VenuPosted Nov 12, 2015, 8:36 AM
Nice