Re: how to avoid repeating expensive computation in select - Mailing list pgsql-general

From Merlin Moncure
Subject Re: how to avoid repeating expensive computation in select
Date
Msg-id AANLkTimLo8MAuU-yWzAhFbO=_-6v0MKiuUF82tJ2FCfp@mail.gmail.com
Whole thread Raw
In response to Re: how to avoid repeating expensive computation in select  (Orhan Kavrakoglu <orhan@tart.com.tr>)
List pgsql-general
On Tue, Mar 1, 2011 at 2:51 AM, Orhan Kavrakoglu <orhan@tart.com.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

pgsql-general by date:

Previous
From: Tom Lane
Date:
Subject: Re: Per-session memory footprint (9.0/windows)
Next
From: Jasmin Dizdarevic
Date:
Subject: Re: PG on two nodes with shared disk ocfs2 & drbd