Home > Back-end >  is it possible to do a conditional concat?
is it possible to do a conditional concat?

Time:09-22

I have a query that pulls different data but for one field it concats its since the URL is partially filled in my db

select blah, blah2, blah3, concat('https://my_url.com', g.logourl ) as logourl

but the problem is if logourl is blank then I just get https://my_url.com instead of the full URL. This is having down stream impact.

Is there a way to only concat if logurl is not null?

CodePudding user response:

You can try using case when expression

select blah, blah2, blah3, 
 case when g.logourl is not null or g.logourl<>''
     then concat('https://my_url.com', g.logourl ) end as logourl

CodePudding user response:

You can use:

(case when g.logourl is not null  then 'https://my_url.com' || g.logourl 
 end) as logourl

If you want to avoid an empty string (and NULL) you can use:

(case when g.logourl <> ''  then 'https://my_url.com' || g.logourl 
 end) as logourl

If you want to eliminate a string of spaces:

(case when replace(g.logourl, ' ', '') <> ''  then 'https://my_url.com' || g.logourl 
 end) as logourl

CodePudding user response:

If you want the output to be null if logurl is null, then you can use the concat operator || instead of the concat() function

select 'a' || null;
 ?column?
----------

(1 row)
  • Related