Re: getting around---division by zero on numeric - Mailing list pgsql-general

From Tom Lane
Subject Re: getting around---division by zero on numeric
Date
Msg-id 21751.1129733638@sss.pgh.pa.us
Whole thread Raw
In response to getting around---division by zero on numeric  (Tim Nelson <timnelson@phreaker.net>)
List pgsql-general
Tim Nelson <timnelson@phreaker.net> writes:
> I am getting division by zero on a calculated field ( sum(sales) is 0 )
> and I can't find a way around this.  I figured out you can't use an
> aggregate in a where, and using having the parser must (obviously)
> evaluate the select fields before considering teh having clause.

Nothing "obvious" about that, in fact the spec says the opposite.

> select
>     type,
>     sum(sales),
>     sum(cost),
>     (sum(sales) * sum(cost) / sum(sales)) * 100
> from test
> group by 1
> having sum(sales) != 0

This should indeed work.  If it doesn't, it means you are using an old
version of Postgres.  It was fixed in 7.4.4:

2004-07-10 14:39  tgl

    * src/backend/executor/: nodeAgg.c (REL7_4_STABLE), nodeAgg.c: Test
    HAVING condition before computing targetlist of an Aggregate node.
    This is required by SQL spec to avoid failures in cases like
    SELECT sum(win)/sum(lose) FROM ... GROUP BY ... HAVING sum(lose) >
    0; AFAICT we have gotten this wrong since day one.  Kudos to Holger
    Jakobs for being the first to notice.

As other respondents noted, you can work around the problem in various
ways ... but you shouldn't have to.

            regards, tom lane

pgsql-general by date:

Previous
From: Berend Tober
Date:
Subject: Re: getting around---division by zero on numeric
Next
From: Csaba Nagy
Date:
Subject: log_min_duration_statement oddity