Concatenate Columns in PostgreSQL in the Select Statement

In order to join multiple columns into one string in the select statement in PostgreSQL, one would usually use the concatenation operator ||

SELECT 'devlabs' || '.' || 'ninja' AS devlabs;

or (combine different columns):

SELECT article.slug || '/' || article.id FROM articles;

The concatenation operator will return NULL in the case if one of the columns is null:

SELECT 'test' || ' ' || NULL AS test_null;

Which can lead to additional effort to handle columns with null values.

Since PostgreSQL 9.1 we can also use the CONCAT function, which will ignore the NULL values. The CONCAT can be called with a list of arguments which has to be convertible to a string (char, varchar, text).

SELECT CONCAT ('devlabs', '.', 'ninja');

Besides the CONCAT function, postgreSQL offers also the CONCAT_WS which joins strings into one separated by a provided separator (and also ignores NULL values like the CONCAT function):

CONCAT_WS(separator, s1, s2, s3, ...);
SELECT CONCAT_WS(',', 'a', 'b', 'c') as test;