Thursday, 24 May 2012

SQL COALESCE‏


Coalesce function is a good feature in SQL to concatenate data from multiple columns of that row and return a single field value. During the concatenation the null value will be ignore and it retrieve non null values.

Consider a scenario you need to retrieve contact number of an employee from an employee table. It is not necessary that all type of contact number is available in the employee table. We need to retrieve the employee contact number. So using the coalesce function we can retrieve the employee contact number.

Employee Table
Name
Business_Phone
Cell_Phone
Home_Phone
Marsh
531-2531
622-7813
565-9901
Don
NULL
772-5588
312-4088
Parker
NULL
NULL
594-7477
and we want to find out the best way to contact each person according to the following rules:
1. If a Employee has a business phone, use the business phone number.
2. If a Employee does not have a business phone and has a cell phone, use the cell phone number.
3. If a Employee does not have a business phone, does not have a cell phone, and has a home phone, use the home phone number.
We can use the COALESCE function to achieve our goal:
SELECT Name, COALESCE(Business_Phone, Cell_Phone, Home_Phone) Contact_Phone 
FROM Contact_Info;
Result:
Name
Contact_Phone
Marsh
531-2531
Don
772-5588
Parker
594-7477

No comments:

Post a Comment