PostgreSQL中 nullif函数和coalesce函数使用方法

NULLIF函数:如果提供的表达式相等,nullif 函数返回一个空值。

                       否则,它将返回第一个表达式作为结果。 

--nullif function returns a null value if provided expressions are equal. 
--If two expressions provided are equal, then it provides a null value; 
--otherwise, it will return the first expression as a result.

select nullif(50,50);
--输出结果
NULL

select nullif('','');
select nullif(null,null);
--输出结果
NULL

select nullif('50', null)
--输出结果
50

select nullif(null, '50')
--输出结果
NULL

select nullif(null, '')
--输出结果
NULL

select nullif('', null)
--输出结果
空字符串

 coalesce函数:返回第一个非空值

--COALESCE (Argument1, Argument2,….,ArgumentN);
--COALESCE  returns as first non-null value as a result
--coalesce返回第一个非空值
select coalesce(null, 50);
select coalesce(50, null);
--返回结果均为50

select coalesce(null,null);
--返回NULL

select coalesce('','');
--返回空字符串

select coalesce (NULL, 20, 30, 40, 50);
--返回20

select coalesce(null, '')
--返回空字符串

一般将两者结合起来使用


--如果columnA字段为NULL或者是空字符串'',使用nullif函数首先将其与空字符串'',得到NULL
    --因为如果ColumnA为NULL, 则nullif(NULL,'')为NULL
    --因为如果ColumnA为'',   则nullif('','')为NULL
--结合coalesce函数取第一个非空值,则可以得到字符串'0'
select coalesce(nullif(columnA, ''), '0')

参考链接:https://www.educba.com/postgresql-nullif/

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值