Re: sum() - unexpected results.

From: Tod McQuillin <devin(at)spamcop(dot)net>
To: Jeff MacDonald <jeff(at)hub(dot)org>
Cc: <pgsql-general(at)postgresql(dot)org>
Subject: Re: sum() - unexpected results.
Date: 2001-02-06 05:33:43
Message-ID: Pine.GSO.4.31.0102052328510.6542-100000@sysadmin
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Mon, 5 Feb 2001, Jeff MacDonald wrote:

> I got some unexpected results from a sum().. just wondering
> if it's a bug of any sort, or if i just should have been expecting it..
>
> SELECT sum(foo) FROM mytable WHERE active = 1;
>
> Now lets say that no rows are active = 1, then this query returns
> 1 blank row..

It is returning NULL, which is what sum() returns when it is asked to sum
0 rows.

> I would have expected either
> 1: a result of zero
> or
> 2: zero rows returned..

If you want a result of zero, use

SELECT coalesce(sum(foo), 0) ...

This is the way SQL-92 says it should be. On page 126 of the document at
http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt it says:

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

Case:

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

(TXA refers to the table constructed from the summed column).
--
Tod McQuillin

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Paul M Foster 2001-02-06 05:40:39 Re: MySQL file system
Previous Message GH 2001-02-06 04:17:20 Re: DBDesign Question