Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: if field is empty assign a value

Here's my query:

$sql = "SELECT u.PHONE , u.STATE , if (uo.CHANNEL='','web',channel) as TYPE FROM user
LEFT JOIN user_oferts uo ON u.PHONE=uo.PHE_USER 
WHERE (u.STATE='active') ";

And it is working great, I get what I want BUT for channel that is empty.

I need channel to be "web" if it is not "wap", this way channel will not be empty or null or nothing. How can I do that? What am I doing wrong?

Thanks a lot

like image 386
ADM Avatar asked Feb 26 '23 13:02

ADM


1 Answers

select 
...
case when channel = '' then 
   web 
else 
   channel 
end as TYPE....

using the CASE statement.

i.e. for your case

$sql = "SELECT u.PHONE , u.STATE 
, case when coalesce(uo.CHANNEL, '') = '' then 'web' else channel end as TYPE 
FROM user
LEFT JOIN user_oferts uo ON u.PHONE=uo.PHE_USER 
WHERE (u.STATE='active') ";

Edit: added coalesce to deal with possible NULL values.

like image 70
davek Avatar answered Feb 28 '23 03:02

davek