postgres 判断null_sql – 为什么null || null返回一个空值但是concat(null,null)在postgres中返回一个空字符串?...

这篇博客探讨了在PostgreSQL中,concat()函数和字符串连接操作符||在处理空值(NULL)时的行为差异。concat()函数会忽略NULL值,当所有参数都为NULL时返回空字符串。而||操作符要求至少有一个非NULL的字符串输入,否则会产生NULL结果。此外,还提到了PostgreSQL 8.3之前的一些历史变化,以及不同函数和操作符对非字符串类型输入的处理方式。
摘要由CSDN通过智能技术生成

我试图理解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.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值