HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Does the || operator in Postgres result in a blank result if one of the columns is blank?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
resulttheoperatorpostgrescolumnsblankonedoes

Problem

I am running a query in Postgres using the || operator to concatenate some columns and it seems where one of the columns is blank the whole result is blank. Is that normal || behaviour?

With "blank" I mean NULL.

Solution

Depends what "blank" means, NULL or the empty string.

-
If it means NULL, then yes, that's normal. SELECT 'ab' || NULL ; will return null.

-
If it means an empty string, then no. SELECT 'ab' || '' ; will return 'ab'.

To avoid the issue, you can convert the nulls to empty string with COALESCE():

SELECT 
    COALESCE(str1, '') || COALESCE(str2, '') || ... || COALESCE(strN, '')


or use CONCAT() or CONCAT_WS() functions - which ignore nulls:

SELECT 
    CONCAT(str1, str2, ..., strN)

SELECT 
    CONCAT_WS('', str1, str2, ..., strN)

Code Snippets

SELECT 
    COALESCE(str1, '') || COALESCE(str2, '') || ... || COALESCE(strN, '')
SELECT 
    CONCAT(str1, str2, ..., strN)

SELECT 
    CONCAT_WS('', str1, str2, ..., strN)

Context

StackExchange Database Administrators Q#170999, answer score: 6

Revisions (0)

No revisions yet.