Why does TSQL operator + behave differently than a

2019-07-15 03:17发布

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条回答
ら.Afraid
2楼-- · 2019-07-15 03:28

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.

查看更多
登录 后发表回答