Why SUM(null) is not 0 in Oracle?

前端 未结 6 1969
轻奢々
轻奢々 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:40

    If you are looking for a rationale for this behaviour, then it is to be found in the ANSI SQL standards which dictate that aggregate operators ignore NULL values.

    If you wanted to override that behaviour then you're free to:

    Sum(Coalesce(,0))
    

    ... although it would make more sense with Sum() to ...

    Coalesce(Sum(),0)
    

    You might more meaningfully:

    Avg(Coalesce(,0))
    

    ... or ...

    Min(Coalesce(

    Other ANSI aggregation quirks:

    1. Count() never returns null (or negative, of course)
    2. Selecting only aggregation functions without a Group By will always return a single row, even if there is no data from which to select.

    So ...

    Coalesce(Count(),0)
    

    ... is a waste of a good coalesce.

提交回复
热议问题