Re: I probably don't understand aggregates. - Mailing list pgsql-novice

From Tom Lane
Subject Re: I probably don't understand aggregates.
Date
Msg-id 29964.1402524573@sss.pgh.pa.us
Whole thread Raw
In response to I probably don't understand aggregates.  (Markus Neumann <markus.neumann@math.uzh.ch>)
List pgsql-novice
Markus Neumann <markus.neumann@math.uzh.ch> writes:
> if I call
>    SELECT myAggrFunction(x) FROM table;
> I get the correct and expected output.

> but when myAggrFunction gets called inside the "wrapper"-function, the
> finalfunction gets executed before all rows are processed and hence I
> get a "Division by zero" error.

> E.g.
>    SELECT myWrapperFunction(x) FROM table;
>    ERROR: division by zero

> myWrapperFunction would look something like:

>    BEGIN
>      M := myAggrFunction(x);
>      --do some more stuff
>      RETURN M;
>    END;

That is certainly not going to do what you presumably want.
The outer query doesn't think that the wrapper function is an
aggregate; it's just a plain scalar function that will be called
separately on each row of the table.  Meanwhile, the best way
to think about what's happening inside the wrapper is that
     M := myAggrFunction(x);
is equivalent to
     SELECT myAggrFunction(x) INTO M FROM anonymous-one-row-table;
or if you're an Oracle refugee,
     SELECT myAggrFunction(x) INTO M FROM dual;

So the aggregate is evaluated over just one row, and I suppose the
zero-divide error happens because your final function is failing
to cope with that case.

            regards, tom lane


pgsql-novice by date:

Previous
From: David G Johnston
Date:
Subject: Re: I probably don't understand aggregates.
Next
From: Markus Neumann
Date:
Subject: Re: I probably don't understand aggregates.