Re: Unexpected behavior with CASE statement

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: "Jimmy Choi" <yhjchoi(at)gmail(dot)com>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Unexpected behavior with CASE statement
Date: 2007-10-03 23:15:28
Message-ID: 4287.1191453328@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

"Jimmy Choi" <yhjchoi(at)gmail(dot)com> writes:
> select
> metric_type,
> case metric_type
> when 0 then
> sum (1 / val)
> when 1 then
> sum (val)
> end as result
> from metrics
> group by metric_type

The reason this does not work is that the aggregate functions are
aggregated without any knowledge of how they might ultimately be used
in the final output row. The fact that the CASE might not actually
demand the value of an aggregate at the end doesn't stop the system from
having to compute it.

You could use a CASE *inside* the SUM() to prevent division by zero
while forming the sum, but on the whole this query seems rather badly
designed. Consider

SELECT 0, sum(1/val) FROM metrics WHERE metric_type = 0
UNION ALL
SELECT 1, sum(val) FROM metrics WHERE metric_type = 1
UNION ALL
...

regards, tom lane

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Andreas Strasser 2007-10-04 01:07:17 Design Question (Time Series Data)
Previous Message Tom Lane 2007-10-03 22:17:01 Re: PITR Recovery and out-of-sync indexes