Let us understand the use of COALESCE with the help of an example.
In this example, the Candidate table is shown to include three columns with information about a Candidate:
1. Candidate_id
2. PrimaryEmail
3. SecondaryEmail
COALESCE in the SELECT statement below, selects the PrimaryEmail if it is not null. If the PrimaryEmail is null then SecondaryEmail will be selected. If both PrimaryEmail and SecondaryEmail is present then only PrimaryEmail is selected. So, COALESCE returns the first nonnull column among the list of columns passed. If both PrimaryEmail and SecondaryEmail is NULL, COALESCE returns NULL.
Thanks venkat! this is the thing which i came across for the first time now i will start make use of it in real time scenarios
ReplyDeleteyup realy great thanks from my side vijay raj gupta
ReplyDeletebut the problem is that it also displays null columns in that table if some of the columns in having both primary and sec is null.....
ReplyDeleteThe best website ever for the concepts to understand in a solid way.... Thank you Venkat.
ReplyDeleteCOALESCE can also be used to concatenate multiple rows as a single comma separated row.
ReplyDeletedeclare @sample varchar(50)
select @sample = @sample + COALESCE(@sample, ',') + colname
from tablename
Thanks
ReplyDeleteThis way make easy in practice
COALESCE can also be used to concatenate multiple rows as a single comma separated row use bellow query(SLIGHT MODIFIED ABOVE QUERY)
ReplyDeleteDECLARE @Names VARCHAR(MAX)
SELECT @Names = COALESCE(@Names + ', ','') + NAME FROM EMPLOYEE
SELECT @Names
but name should not a null value in name if any null value exist then use where name is not null
DeleteThanks Venkat..I have never use COALESCE as I was not aware of it. but now I came across it through you article.
ReplyDeleteAwesome explanation...toooooo gooooood..
ReplyDeleteWe also can use CASE instead of using COALESCE function, so my concern which one is fast
ReplyDeleteAbove Questions are using Fresher Or Experience candidate?
ReplyDeleteDECLARE @Names VARCHAR(MAX)
ReplyDeleteSELECT @Names = COALESCE(@Names + ', ','') + St_Fname FROM
( select s.St_Fname from Student as s)AS D
SELECT @Names as first_Name
DECLARE @Names VARCHAR(MAX)
SELECT @Names = COALESCE(@Names + ', ','') +
cast(ISNULL(St_Fname, '') as VARCHAR) FROM
( select s.St_Fname from Student as s)AS D
SELECT @Names as first_Name
Why do the results of these two queries different?