我试图理解concat()和||之间的区别在postgres中使用空值.如果concat的两边都为null,为什么concat()返回一个空字符串?
以此查询为例:
SELECT concat(NULL,NULL) AS null_concat, NULL||NULL AS null_pipes,
concat(NULL,NULL) IS NULL is_concat_null, NULL||NULL IS NULL is_pipe_null
将返回:
我知道concat()会忽略null,但是如果concat中的所有值都为null,那么预期的结果是不是null?这是postgres中所有函数的典型行为吗?在这个场景中,我在文档中找不到任何内容.
编辑:
我有一个想法,也许这是任何字符串函数的预期结果,但似乎并非如此.如果传递null值,则upper()和left()都返回null:
SELECT concat(NULL), NULL||NULL, UPPER(null), left(NULL,1)
结果:
最佳答案 在concat()函数中:
text concat(str "any",...) Concatenate all arguments. NULL arguments are ignored.
注意:忽略NULL参数.
想象一下:
输入参数concat()是动态的.
所以当我们写:concat(‘a’,null,null,null,null)=>我们写了:concat(‘a’)
(与||运算符相反,NULL破坏了所有内容)
在||操作符:
the string concatenation operator (||) still accepts non-string input,
so long as at least one input is of a string type
所以NULL || NULL语法错误
但为什么不给错误?
因为在concat操作中,如果我们不拒绝NULL(就像concat函数一样),它们将压倒一切
SELECT NULL ||’aaa’||’bbb’||’ccc’||’ddd’
输出:
空值
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.