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 following 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.
For example:
We have three different PhoneNumber column for a single User and may be User has only one or two PhoneNumber, and now the 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 on this:
Create sample table and data:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
CREATE TABLE tbl_UserPhoneNumbers ( UserID INTEGER IDENTITY(1,1) ,UserName VARCHAR(50) ,PhoneNumber1 CHAR(10) ,PhoneNumber2 CHAR(10) ,PhoneNumber3 CHAR(10) ,CONSTRAINT pk_tbl_UserPhoneNumbers_UserID PRIMARY KEY(UserID) ) GO INSERT INTO tbl_UserPhoneNumbers (UserName,PhoneNumber1,PhoneNumber2,PhoneNumber3) VALUES ('Anvesh','9898245852',NULL ,NULL) ,('Roy',NULL,'8759654122',NULL) ,('Eric',NULL,NULL,'9565859812') ,('Lurin','9898652312','9685741252',NULL) GO |
You can find some NULL field in the above result.
Now use COALESCE() to SELECT first NOT NULL PhoneNumber:
1 2 3 4 5 |
SELECT UserID ,UserName ,PhoneNumber=COALESCE(PhoneNumber1,PhoneNumber2,PhoneNumber3) FROM tbl_UserPhoneNumbers |
The Result: