Re: Optimizing queries - Mailing list pgsql-performance

From Tom Lane
Subject Re: Optimizing queries
Date
Msg-id 19962.1155134346@sss.pgh.pa.us
Whole thread Raw
In response to Re: Optimizing queries  (Patrice Beliveau <pbeliveau@avior.ca>)
List pgsql-performance
Patrice Beliveau <pbeliveau@avior.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

pgsql-performance by date:

Previous
From: Michal Taborsky - Internet Mall
Date:
Subject: 3-table query optimization
Next
From: Tom Lane
Date:
Subject: Re: 3-table query optimization