Re: BUG #4057: SUM returns NULL when given no rows - Mailing list pgsql-bugs

From Tom Lane
Subject Re: BUG #4057: SUM returns NULL when given no rows
Date
Msg-id 3159.1206490266@sss.pgh.pa.us
Whole thread Raw
In response to BUG #4057: SUM returns NULL when given no rows  ("Reginald Drake" <reggie.drake@gmail.com>)
List pgsql-bugs
"Reginald Drake" <reggie.drake@gmail.com> writes:
> Doing something like "SELECT SUM(some_integer_column) FROM some_table WHERE
> FALSE" gives me NULL, where I would expect 0. Since COUNT does give a
> meaningful value when applied to zero columns, maybe SUM should do the same.

You might expect that, but the SQL spec is entirely clear on the matter:

            Case:

            a) If the <general set function> COUNT is specified, then the
              result is the cardinality of TXA.

            b) If AVG, MAX, MIN, or SUM is specified, then

              Case:

              i) If TXA is empty, then the result is the null value.
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

             ii) If AVG is specified, then the result is the average of the
                 values in TXA.

            iii) If MAX or MIN is specified, then the result is respec-
                 tively the maximum or minimum value in TXA. These results
                 are determined using the comparison rules specified in
                 Subclause 8.2, "<comparison predicate>".

             iv) If SUM is specified, then the result is the sum of the
                 values in TXA. If the sum is not within the range of the
                 data type of the result, then an exception condition is
                 raised: data exception-numeric value out of range.

            regards, tom lane

pgsql-bugs by date:

Previous
From: "Reginald Drake"
Date:
Subject: BUG #4057: SUM returns NULL when given no rows
Next
From: "David Rowley"
Date:
Subject: Re: Possible problem with EXTRACT(EPOCH FROM TIMESTAMP)