Re: BUG #14399: Order by id DESC causing bad query plan

From: "David G(dot) Johnston" <david(dot)g(dot)johnston(at)gmail(dot)com>
To: jkoceniak(at)mediamath(dot)com
Cc: "pgsql-bugs(at)postgresql(dot)org" <pgsql-bugs(at)postgresql(dot)org>
Subject: Re: BUG #14399: Order by id DESC causing bad query plan
Date: 2016-11-01 23:41:42
Message-ID: CAKFQuwY=54PRU1rwU86xaQMnL+5HfDngJr5=2HpZ1QyDQYDfVg@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-bugs

On Thu, Oct 27, 2016 at 5:16 PM, <jkoceniak(at)mediamath(dot)com> wrote:

> The following bug has been logged on the website:
>
> Bug reference: 14399
> Logged by: Jamie Koceniak
> Email address: jkoceniak(at)mediamath(dot)com
> PostgreSQL version: 9.4.6
> Operating system: Linux
> Description:
>
> One table has 2M records (orders) joining to another table with 75K records
> (customers).
>
> Query:
> select * FROM
> orders t1
> JOIN customer t2 ON (t1.customer_id = t2.id)

WHERE
> t2.id IN (select distinct customer_id from valid_customers)

ORDER BY t1.id
> LIMIT 10 ;
>

​Bug potential aside the better way to write ​that is to use a proper
semi-join (i.e., EXISTS)

SELECT *
FROM order t1
JOIN customer t2 ON (t1.customer_id = t2.id)
WHERE EXISTS (SELECT 1 FROM valid_customers t3 WHERE t3.customer_id = t2.id)
ORDER BY t1.id
LIMIT 10;

Note too that your query plan has a "function scan" node unlike what your
query implies...

Sorry I can't be of more help with the information you've provided.

David J.

In response to

Responses

Browse pgsql-bugs by date

  From Date Subject
Next Message Tom Lane 2016-11-01 23:51:05 Re: BUG #14408: Schema not found error when 2 or more indices declared on temporary table
Previous Message Victor Colborn 2016-11-01 23:06:10 Re: BUG #14408: Schema not found error when 2 or more indices declared on temporary table