Re: how to avoid repeating expensive computation in select

From: Merlin Moncure <mmoncure(at)gmail(dot)com>
To: Orhan Kavrakoglu <orhan(at)tart(dot)com(dot)tr>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: how to avoid repeating expensive computation in select
Date: 2011-03-02 23:50:25
Message-ID: AANLkTimLo8MAuU-yWzAhFbO=_-6v0MKiuUF82tJ2FCfp@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Tue, Mar 1, 2011 at 2:51 AM, Orhan Kavrakoglu <orhan(at)tart(dot)com(dot)tr> wrote:
>> I would like to know if there is a way in PostgreSQL to avoid repeating an
>> expensive computation in a SELECT where the result is needed both as a
>> returned value and as an expression in the WHERE clause.
>
> I think I've seen it said here that PG avoids redundant multiple
> calculations of an expression.
>
> Even so, have you thought about using subqueries?
>
>>   SELECT id, expensivefunc(value) AS score FROM mytable
>>      WHERE id LIKE '%z%' AND expensivefunc(value)>  0.5;
>
> SELECT id, expensivefunc(value) FROM (
> (SELECT id, value FROM mytable WHERE id LIKE '%z%')
> ) WHERE expensivefunc(value) > 0.5;
>
> or even
>
> SELECT id, score FROM (
> SELECT id, expensivefunc(value) AS score FROM (
> (SELECT id, value FROM mytable WHERE id LIKE '%z%')
> )
> ) WHERE score > 0.5

you missed the point: even when you use subqueries postgres can inline
them, 'unsubquerying' your query. I think the OP nailed probably the
best and most logical approach -- use a CTE. It's more formal, and
while not super efficient today, isn't terrible.

merlin

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Rob Sargent 2011-03-03 00:13:51 close connection more expensive that open connection?
Previous Message Tom Lane 2011-03-02 22:42:42 Re: Per-session memory footprint (9.0/windows)