Re: Evaluate only one CASE WHEN in a select - Mailing list pgsql-general

From Tom Lane
Subject Re: Evaluate only one CASE WHEN in a select
Date
Msg-id 4956.1176409810@sss.pgh.pa.us
Whole thread Raw
In response to Re: Evaluate only one CASE WHEN in a select  ("dcrespo" <dcrespo@gmail.com>)
Responses Re: Evaluate only one CASE WHEN in a select
List pgsql-general
"dcrespo" <dcrespo@gmail.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

pgsql-general by date:

Previous
From: Tom Lane
Date:
Subject: Re: deadlock
Next
From: Scott Marlowe
Date:
Subject: Re: deadlock