MySql – Get different field based on null – coalesce

Displaying different field based on null. (ex: display alias field if it is not null and name field if alias field is null. i.e., if user has alias and name both u just have to show alias if he has no alias u have to show name)

if rs is result then in php u will so

foreach($rs as $r)
{
   if($r['alias']=="")
   {
     echo $r['name'];
   }
   else
   {
     echo $r['alias'];
   }
}

but U guys can do a null check and different field value at query level

selet coalesce(alias,name) as name  from profiles

coalesce will give first not null of what u sent. i.e., coalesce(null,null,0,null,’a') will just give 0

so no need for php server to do an if condition for each row

so code can just be

foreach($rs as $r)
{
   echo $r['name'];
}

hope this useful info share it among php and mysql developers . So I prefer doing many code operations in query level .

ha ha. only few of php and mysql coders using case statement much .

Thanks for reading - your comments encourage me, Rama Krishna Chunduri
Share