Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sql query to get this result

Tags:

select

mysql

Consider i have a user table and I have three columns mobilePhone,homePhone and workPhone...

I have to select homePhone for every user as first pref
if there is no value
   I'll go for mobilePhone and
   if there is no value for it
      I ll go for workPhone....

Any suggestion how it can be done in mysql..

like image 260
bala3569 Avatar asked Dec 28 '22 20:12

bala3569


2 Answers

Try using Sql Server COALESCE (Transact-SQL),

Returns the first nonnull expression among its arguments.

Same goes for MySql COALESCE(value,...)

Returns the first non-NULL value in the list, or NULL if there are no non-NULL values.

Something like

SELECT  COALESCE(homePhone, mobilePhone, workPhone) ContactPhone
FROM    Users
like image 162
Adriaan Stander Avatar answered Dec 31 '22 13:12

Adriaan Stander


You want the Coalesce function which returns the first non-null value:

Select Coalesce(homephone, mobilephone, workphone) Phone
From `user`

Coalesce does exist in MySQL. It is an ANSI defined function.

Coalesce function (MySQL).

like image 40
Thomas Avatar answered Dec 31 '22 13:12

Thomas