Re: Optimizing queries

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Patrice Beliveau <pbeliveau(at)avior(dot)ca>
Cc: pgsql-performance(at)postgresql(dot)org
Subject: Re: Optimizing queries
Date: 2006-08-09 14:39:06
Message-ID: 19962.1155134346@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-performance

Patrice Beliveau <pbeliveau(at)avior(dot)ca> writes:
> Tom Lane wrote:
>> PG 8.1 will not reorder WHERE clauses for a single table unless it has
>> some specific reason to do so (and AFAICT no version back to 7.0 or so
>> has done so either...) So there's something you are not telling us that
>> is relevant.

> here is my query, and the query plan that result

> explain select * from (
> select * from sales_order_delivery
> where sales_order_id in (
> select sales_order_id from sales_order
> where closed=false
> )
> ) as a where outstandingorder(sales_order_id, sales_order_item,
> date_due) > 0;

So this isn't a simple query, but a join. PG will generally push
single-table restrictions down to the individual tables in order to
reduce the number of rows that have to be processed at the join.
In this case that's not a win, but the planner doesn't know enough
about the outstandingorder() function to realize that.

I think what you need is an "optimization fence" to prevent the subquery
from being flattened:

explain select * from (
select * from sales_order_delivery
where sales_order_id in (
select sales_order_id from sales_order
where closed=false
)
OFFSET 0
) as a where outstandingorder(sales_order_id, sales_order_item,
date_due) > 0;

Any LIMIT or OFFSET in a subquery prevents WHERE conditions from being
pushed down past it (since that might change the results). OFFSET 0 is
otherwise a no-op, so that's what people usually use.

regards, tom lane

In response to

Browse pgsql-performance by date

  From Date Subject
Next Message Tom Lane 2006-08-09 15:08:59 Re: 3-table query optimization
Previous Message Patrice Beliveau 2006-08-09 14:23:01 Re: Optimizing queries