Search code examples
mysqlsqlinner-join

mysql select statement bring back column if column is empty


Is there a way to select col1 if col2 is empty else use col2? col1 will never be empty.

select 
ug.permissions,
g.name,
g.display,
g.permissions
from system.users_groups as ug
inner join system.groups as g on ug.group_id = g.id
where ug.user_id = ?

The above statement brings back both permissions columns, I would like to bring back only one permissions column.

if ug.permissions = '' then use g.permissions


Solution

  • Using COALESCE and NULLIF:

    select 
    COALESCE(NULLIF(ug.permissions,''),g.permissions) as permissions ,
    g.name,
    g.display
    from system.users_groups as ug
    inner join system.groups as g on ug.group_id = g.id
    where ug.user_id = ?
    

    Using CASE:

    select 
    CASE WHEN ug.permissions = '' OR ug.permissions IS NULL
    THEN
         g.permissions
    ELSE
         ug.permissions 
    END as permissions ,
    g.name,
    g.display
    from system.users_groups as ug
    inner join system.groups as g on ug.group_id = g.id
    where ug.user_id = ?