X-Original-To: pgsql-sql@postgresql.org Received: from localhost (developer.postgresql.org [64.117.224.193]) by developer.postgresql.org (Postfix) with ESMTP id 3DAC2924DDC for ; Fri, 30 May 2003 13:51:54 -0400 (EDT) Received: from developer.postgresql.org ([64.117.224.193]) by localhost (developer.postgresql.org [64.117.224.193:10024]) (amavisd-new) with ESMTP id 61906-01 for ; Fri, 30 May 2003 13:51:53 -0400 (EDT) Received: from sss.pgh.pa.us (unknown [192.204.191.242]) by developer.postgresql.org (Postfix) with ESMTP id 6F399924DBE for ; Fri, 30 May 2003 13:51:53 -0400 (EDT) Received: from sss2.sss.pgh.pa.us (tgl@localhost [127.0.0.1]) by sss.pgh.pa.us (8.12.9/8.12.9) with ESMTP id h4UHpoU6010648; Fri, 30 May 2003 13:51:50 -0400 (EDT) To: Richard Huxton Cc: C F , pgsql-sql@postgresql.org Subject: Re: CASE returning multiple values (was SQL Help) In-reply-to: <200305301740.06691.dev@archonet.com> References: <20030530154703.37238.qmail@web20415.mail.yahoo.com> <200305301740.06691.dev@archonet.com> Comments: In-reply-to Richard Huxton message dated "Fri, 30 May 2003 17:40:06 +0100" Date: Fri, 30 May 2003 13:51:49 -0400 Message-ID: <10647.1054317109@sss.pgh.pa.us> From: Tom Lane X-Virus-Scanned: by amavisd-new X-Archive-Number: 200305/575 X-Sequence-Number: 13740 Richard Huxton 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