Re: CASE returning multiple values (was SQL Help)

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Richard Huxton <dev(at)archonet(dot)com>
Cc: C F <tacnaboyz(at)yahoo(dot)com>, pgsql-sql(at)postgresql(dot)org
Subject: Re: CASE returning multiple values (was SQL Help)
Date: 2003-05-30 17:51:49
Message-ID: 10647.1054317109@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Richard Huxton <dev(at)archonet(dot)com> writes:
> On Friday 30 May 2003 4:47 pm, C F wrote:
>> select
>> (case when column1 = column2 then column3 end) as alias1,
>> (case when column1 = column2 then column4 end) as alias2,
>> (case when column1 = column2 then column5 end) as alias3,
>> (case when column6 = column7 then column8 end) as alias4

> Can you explain what it is you're trying to acheive - real
> fields/schemas etc?

Yeah. I can't help feeling that this problem really means you've chosen
a bad database schema.

Given the problem as posed, I can only offer one suggestion: you could
avoid writing out the case conditions N times by using a sub-select to
factor out common subexpressions:

select
(case when cond1 then column3 end) as alias1,
(case when cond1 then column4 end) as alias2,
(case when cond1 then column5 end) as alias3,
(case when cond2 then column8 end) as alias4
from
(select
column1 = column2 as cond1,
column6 = column7 as cond2,
column3, column4, ...
from
... rest of query as in original ...
) ss;

One should not mistake this for an efficiency improvement, since more
than likely the planner will flatten it into the same querytree as the
original form. But it might be more readable or easier to code this
way.

But give us some details about your table setup and why you find
yourself needing to do this in the first place. Maybe there's a
better design.

regards, tom lane

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message C F 2003-05-30 18:01:13 Re: CASE returning multiple values (was SQL Help)
Previous Message Sean Chittenden 2003-05-30 17:12:38 Re: "record" datatype - plpgsql