Postgresql – String concatenation with a null seems to nullify the entire string – is that desired behavior in Postgres

concatenationpostgresqlstring

In Postgres:

select 'test' || null  returns null

I was expecting it would otherwise return 'test'.

Is this desired behavior? Seems weird that string concatenation with a null value would nullify the entire string…

Referring to pg docs: http://www.postgresql.org/docs/9.1/static/functions-string.html

"Note: Before PostgreSQL 8.3, these functions would silently accept values of several non-string data types as well, due to the presence of implicit coercions from those data types to text. Those coercions have been removed because they frequently caused surprising behaviors. However, the string concatenation operator (||) still accepts non-string input, so long as at least one input is of a string type, as shown in Table 9-6. For other cases, insert an explicit coercion to text if you need to duplicate the previous behavior."

Given that, using their concat string function example:

concat(str "any" [, str "any" [, …] ])
text Concatenate all arguments. NULL arguments are ignored. concat('abcde', 2, NULL, 22) >> abcde222

Should I just get used to this behavior with '||' concatenation or is this something that should be fixed?

Best Answer

Quote from documentation

Concatenate all arguments. NULL arguments are ignored.

Example

concat('abcde', 2, NULL, 22) 

Returns

abcde222

See more in Documentation