COALESCE with NULL

左心房为你撑大大i 提交于 2019-12-23 07:22:57

问题


I found this snippet of SQL in a view and I am rather puzzled by it's purpose (actual SQL shortened for brevity):

SELECT
    COALESCE(b.Foo, NULL) AS Foo

FROM a
LEFT JOIN b ON b.aId=a.Id

I cannot think of a single reason of the purpose of coalescing with null instead of just doing this:

SELECT
    b.Foo AS Foo

FROM a
LEFT JOIN b ON b.aId=a.Id

Or at the very least don't include the NULL explicitly:

SELECT
    COALESCE(b.Foo) AS Foo

FROM a
LEFT JOIN b ON b.aId=a.Id

I don't know who authored this (so I cannot ask), when it was authored, or for what specific MS SQL Server version it was written for (pre-2008 for sure though).

Is there any valid reason to coalesce with NULL instead of just selecting the column directly? I can't help but laugh and write it off as a rookie mistake but it makes me wonder if there is some "fringe case" that I don't know about.


回答1:


You are right - there is no reason to use:

SELECT COALESCE(b.Foo, NULL)

...because if b.foo is NULL, you might as well just use:

SELECT b.foo

...assuming that you want to know if the value is null.




回答2:


I think there might be an edge case, but it is very historic - it's a bit of a guess but it could surround the situation where b.foo = ' ' e.g. a string of spaces.

Go back far enough in SQL and LTrim(' ') returned null (6 / 6.5), so I am wondering whether Coalesce on an empty string also evaluated it to null, if it did then the mechanism was being used to turn strings of spaces only, into null values? (If all values evaluate as null, Coalesce will return Null.)

It's a guess and I can not test it right away, but shouldn't be hard to check.




回答3:


I would use it if I have multiple columns that I want to check whether all of them are null or not, instead of using AND and IS NOT NULL with every column, I can use a single COALESCE which will make the code simpler and more readable, for example

Select t.a, t.b, t.c, t.d, t.e
from table t
where coalesce(t.a, t.b, t.c, t.d, t.e) is [not] null


来源:https://stackoverflow.com/questions/1766905/coalesce-with-null

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