Re: Evaluate only one CASE WHEN in a select

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: "dcrespo" <dcrespo(at)gmail(dot)com>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Evaluate only one CASE WHEN in a select
Date: 2007-04-12 20:30:10
Message-ID: 4956.1176409810@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

"dcrespo" <dcrespo(at)gmail(dot)com> writes:
> They are exactly the same, that's why I want to evaluate it only once
> and, depending on it, put the corresponding value into two different
> fields that must be returned, instead of evaluating once for each
> field. Any insight?

There's no solution that wouldn't cost you more than double evaluation,
for such a simple expression.

The general solution is to use two levels of SELECT:

select ..., x, x, ...
from (select ..., big-expr as x, ... from ... offset 0) ss;

You need the "offset 0" (which is otherwise a no-op) to prevent the
planner from folding the two selects into a single level and ending up
with two copies of big-expr anyway. The runtime overhead associated
with the extra plan level is about going to eat up whatever you might
save in this example, though with a seriously expensive expression
(for instance, a function that does some fairly expensive SELECT itself)
you might find it worth doing.

regards, tom lane

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Scott Marlowe 2007-04-12 20:33:59 Re: deadlock
Previous Message Tom Lane 2007-04-12 20:21:43 Re: deadlock