Why SUM(null) is not 0 in Oracle?

前端 未结 6 1939
轻奢々
轻奢々 2021-01-04 08:33

It would be appreciated explaining the internal functionality of SUM function in Oracle, when encountering null values:
The result of

select sum(null)          


        
6条回答
  •  星月不相逢
    2021-01-04 08:41

    You're looking at this the wrong way around. SUM() operates on a column, and ignores nulls.

    To quote from the documentation:

    This function takes as an argument any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type. The function returns the same data type as the numeric data type of the argument.

    A NULL has no data-type, and so your first example must return null; as a NULL is not numeric.

    Your second example sums the numeric values in the column. The sum of 0 + null + 1 + 2 is 3; the NULL simply means that a number does not exist here.

    Your third example is not an operation on a column; remove the SUM() and the answer will be the same as nothingness + 1 is still nothingness. You can't cast a NULL to an empty number as you can with a string as there's no such thing as an empty number. It either exists or it doesn't.

提交回复
热议问题