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:
Please share your ideas and opinions about this topic with me, your contribution will add true value to this topic.
If anyone has doubts on this topic then please do let me know by leaving comments or send me an email.
If you like this post, then please share it with others.
Please follow dbrnd.com, I will share my experience towards the success of Database Research and Development Activity.
I put up a post every day, please keep reading and learning.
Discover Yourself, Happy Blogging !
Anvesh M. Patel.