Re: CASE returning multiple values (was SQL Help) - Mailing list pgsql-sql

From Tom Lane
Subject Re: CASE returning multiple values (was SQL Help)
Date
Msg-id 10647.1054317109@sss.pgh.pa.us
Whole thread Raw
In response to Re: CASE returning multiple values (was SQL Help)  (Richard Huxton <dev@archonet.com>)
List pgsql-sql
Richard Huxton <dev@archonet.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


pgsql-sql by date:

Previous
From: Sean Chittenden
Date:
Subject: Re: "record" datatype - plpgsql
Next
From: C F
Date:
Subject: Re: CASE returning multiple values (was SQL Help)