Conditional String Concatenation In PostgreSQL


Answer :

The function concat_ws() does exactly what you want. The first parameter is used as glue between the rest. Nulls are ignored:



select concat_ws('//', owner_addr1, owner_addr2, owner_addr3)


Test:



red=# select concat_ws('//', 'abc', null, null, 'xx', null, 'xyz', null) 
as address;
address
--------------
abc//xx//xyz
(1 row)


Probably most obvious to use a CASE statement. There are 4 cases:



owner_addr2 IS NULL AND owner_addr3 IS NULL => ''       
owner_addr2 IS NULL AND owner_addr3 IS NOT NULL => '//' || owner_addr3
owner_addr2 IS NOT NULL AND owner_addr3 IS NULL => '//' || owner_addr2
owner_addr2 IS NOT NULL AND owner_addr3 IS NOT NULL '//' || owner_addr2 || '//' owner_addr3

SELECT owner_addr1
|| CASE WHEN owner_addr2 IS NULL AND owner_addr3 IS NULL
THEN ''
WHEN owner_addr2 IS NULL AND owner_addr3 IS NOT NULL
THEN '//' || owner_addr3
WHEN owner_addr2 IS NOT NULL AND owner_addr3 IS NULL
THEN '//' || owner_addr2
WHEN owner_addr2 IS NOT NULL AND owner_addr3 IS NOT NULL
THEN '//' || owner_addr2 || '//' || owner_addr3
END AS owner_addr
FROM ...


An alternative is to use 2 CASE statements:



SELECT owner_addr1 
|| CASE WHEN owner_addr2 IS NULL
THEN ''
ELSE '//' || owner_addr2
END
|| CASE WHEN owner_addr3 IS NULL
THEN ''
ELSE '//' || owner_addr3
END as owner_addr
FROM ...


COALESCE can be used instead of CASE:



SELECT owner_addr1 
|| COALESCE('//' || owner_addr2, '')
|| COALESCE('//' || owner_addr3, '') as owner_addr
FROM ...


Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable