This article is half-done without your Comment! *** Please share your thoughts via Comment ***
The COALESCE() is a one of my favourite function in SQL Server.
Using this function, we can check first NOT NULL column or field out of all consecutive columns.
We can pass any number of parameters and it returns the first NOT NULL value.
The COALESCE is ANSI standard function and internally it is working like a CASE..WHEN expression.
We have three different PhoneNumber column for single User and may be User has only one or two PhoneNumber and now requirement is to fetch at least one PhoneNumber from this three different PhoneNumber.
We can easily solve this kind of problem using COALESCE() and it doesn’t need to write big CASE..WHEN expression.
Below is a small demonstration of this:
First, create sample table and data:
CREATE TABLE tbl_UserPhoneNumbers
UserID INTEGER IDENTITY(1,1)
,CONSTRAINT pk_tbl_UserPhoneNumbers_UserID PRIMARY KEY(UserID)
INSERT INTO tbl_UserPhoneNumbers
You can find some NULL field in the above result.
Now use COALESCE() to SELECT first NOT NULL PhoneNumber: