Re: Getting the output of a function used in a where clause

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Rod Taylor <pg(at)rbt(dot)ca>
Cc: Bill Lawrence <bill(dot)lawrence(at)cox(dot)net>, Scott Marlowe <smarlowe(at)g2switchworks(dot)com>, PFC <lists(at)boutiquenumerique(dot)com>, pgsql-sql(at)postgresql(dot)org
Subject: Re: Getting the output of a function used in a where clause
Date: 2005-04-19 02:59:49
Message-ID: 13117.1113879589@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Rod Taylor <pg(at)rbt(dot)ca> writes:
> You can force it with a subselect though:

> SELECT * FROM (SELECT zipcode, zipdist($lat1d,$lon1d,lat,long)
> as distance
> from zipcodes) AS tab where distance <= $dist;

The above will *not* stop zipdist from being run twice, because the
planner will happily flatten the subquery into the outer query,
resulting in the same situation of zipdist() being present twice in
the text of the query.

You could force the issue with

SELECT * FROM (SELECT zipcode, zipdist($lat1d,$lon1d,lat,long)
as distance
from zipcodes OFFSET 0) AS tab where distance <= $dist;

since LIMIT/OFFSET clauses presently disable the flattening
optimization. Keep in mind though that the OFFSET is an absolute
optimization fence: it will result in the subquery being evaluated
completely, even if there were outer conditions that might have
avoided the need to look at some rows. For example, if the query is

SELECT * FROM (SELECT zipcode, zipdist($lat1d,$lon1d,lat,long)
as distance
from zipcodes OFFSET 0) AS tab where distance <= $dist
AND some-other-conditions

then not letting the some-other-conditions migrate down below the
evaluation of zipdist could result in making the query be far slower,
not faster, than you would get if you weren't trying to outsmart the
planner.

In general the system operates on the assumption that function calls
are cheap relative to disk I/O. If that's not true for you, you're
going to have some issues ...

regards, tom lane

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Art - Feping 2005-04-19 03:13:52 How to select from many database ??
Previous Message Michael Fuhr 2005-04-19 02:43:13 Re: can a function return a virtual table?