Wednesday, October 31, 2012

COALESSE: Get first non null value from multiple columns

Ever wondered how to get first non null value from one of many columns?
The usual and cumbersome way to achieve this would be something like this:


CASE
   WHEN (expression1 IS NOT NULL) THEN expression1
   WHEN (expression2 IS NOT NULL) THEN expression2
   ...
   ELSE expressionN
END


And here is how COALESCE will make it simpler


COALESCE(expression1, ...expressionN)

So, if you want to get the first available phone number from HomePhone and OfficePhone present in EmployeePhone table, you should write 

SELECT COALESCE (HomePhone, OfficePhone) from EmployeePhone

No comments: