Why does TSQL operator + behave differently than aggregation function sum()

房东的猫 提交于 2019-12-14 02:14:32

问题


There is a strange behaviour of TSQL:

SELECT 1 + NULL

returns NULL,

while

SELECT sum(someColumn)  

will always return an integer, ignoring null values, unless the whole column is null (in which case it returns null).

What are the design choices behind the decision to make binary operators different in meaning from matching aggregate functions?

Is there a way to overcome this 'limitation', except litteraly stuffing my SQL with coalesce()?

(edited after comments)


回答1:


This behaviour is common to most forms of SQL - in single-row level arithmetic operations, "(b)ecause Null is not a data value, but a marker for an unknown value, using mathematical operators on Null results in an unknown value, which is represented by Null."

By contrast, in aggregate functions (ie. operations across multiple rows), "all aggregate functions perform a Null-elimination step, so that Null values are not included in the final result of the calculation."

Both quoted behaviours have references in the Wikipedia article, citing the ISO/IEC standards where these behaviours are defined.



来源:https://stackoverflow.com/questions/16196713/why-does-tsql-operator-behave-differently-than-aggregation-function-sum

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