Handle LIMIT/OFFSET before select clause (was: Feature request: optimizer improvement)

From: Jim Nasby <jim(at)nasby(dot)net>
To: Joe Love <joe(at)primoweb(dot)com>
Cc: pgsql-hackers(at)postgresql(dot)org
Subject: Handle LIMIT/OFFSET before select clause (was: Feature request: optimizer improvement)
Date: 2013-11-01 20:18:02
Message-ID: F3DF314B-054B-4D92-9B57-B4FBE68637F4@nasby.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

On Oct 31, 2013, at 11:04 AM, Joe Love <joe(at)primoweb(dot)com> wrote:
> In postgres 9.2 I have a function that is relatively expensive. When I write a query such as:
>
> select expensive_function(o.id),o.* from offeirng o where valid='Y' order by name limit 1;
>
> the query runs slow and appears to be running the function on each ID, which in this case should be totally unnecessary as it really only needs to run on 1 row.
>
> When I rewrite the query like so:
>
> select expensive_function(o.id), o.*
> from (select *offering where valid='Y' order by name limit 1) o;
>
> the expensive function only runs once and thus, much faster. I would think that the optimizer could handle this situation, especially when limit or offset is used and the expensive function is not used in a group by, order by or where.

Does anyone know what the SQL standard says about this, if anything? I can't see any way that this would change the result set, but of course if the function has external effects this would make a difference...

In response to

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Jim Nasby 2013-11-01 20:21:43 Re: [BUGS] BUG #8573: int4range memory consumption
Previous Message Tom Lane 2013-11-01 19:28:54 Re: buffile.c resource owner breakage on segment extension