Friday, 10 June 2016

coalesce function in sql

Introduction

When we have multi-value attribute with single or more null values in a Table, the Coalesce() function is very useful.

Using the Code

If you consider the below facts placed in a employee table with IdNameph_noAlt_noOffice no.
idNamePh_ noAlt_ noOffice no
101Albert999999456453321333
102khannullnull123455
103victor112121nullnull
104lovelynullnull1897321
The above Employee table may have single value or three values. If it has single value, then it fills null values with remaining attributes.
When we retrieve the number from employee table, that number Should Not be Null value. To get not nullvalue from employee table, we use Coalesce() function. It returns the first encountered Not Null Value from employee table.
select id , name ,coalesce(Ph_no,Alt_no,Office_no) as contact number from employee 
It returns:
idNameContactnumber
101Albert999999
102khan123455
103victor112121
104lovely1897321