Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

postgresql - String concatenation with a null seems to nullify the entire string - is that desired behavior in Postgres?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Quote from documentation

Concatenate all arguments. NULL arguments are ignored.

Example

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

Returns

abcde222

See more in Documentation


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...