SQL equality/inequality comparison with nullable values

余生颓废 提交于 2019-12-01 04:38:05

问题


first take, kludge solution, sentinel approach(it's imperative that your program should not allow inputting of sentinel value):

 select coalesce(a, -2147483648) = coalesce(b, -2147483648) as is_equal -- a little postgresism

let's say you forgot to block the sentinel value on your program, the user inputted -2147483648 on the B field, and A is null. the code above reports true, should report false, should not report true nor null.

what's the most concise way to compare equality on nullable fields? A == B should just report either true or false only, regardless if the field(s) are nullable or not.


回答1:


Probably IS [NOT] DISTINCT FROM will help here.




回答2:


The operator <=> does what you want in other database engines; is it not in postgres? Otherwise, a is null and b is null or (a is not null and b is not null and a == b) should work. This works because FALSE AND NULL is FALSE.



来源:https://stackoverflow.com/questions/680824/sql-equality-inequality-comparison-with-nullable-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!