Re: Query planner chooses index scan backward instead of better index option

From: Jeff Janes <jeff(dot)janes(at)gmail(dot)com>
To: Seckin Pulatkan <seckinpulatkan(at)gmail(dot)com>
Cc: "pgsql-performance(at)postgresql(dot)org" <pgsql-performance(at)postgresql(dot)org>
Subject: Re: Query planner chooses index scan backward instead of better index option
Date: 2016-11-14 16:50:13
Message-ID: CAMkU=1yG6HnPuj0B4khnsDE4oFM8AWAQd8_xxjk03tYJz_CSBw@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-performance

On Mon, Nov 14, 2016 at 4:01 AM, Seckin Pulatkan <seckinpulatkan(at)gmail(dot)com>
wrote:

> Hi,
>
> On our production environment (PostgreSQL 9.4.5 on
> x86_64-unknown-linux-gnu, compiled by gcc (GCC) 4.8.5 20150623 (Red Hat
> 4.8.5-4), 64-bit), one of our queries runs very slow, about 5 minutes . We
> noticed that it does not use an index that we anticapited it would.
>
> The query is
>
> select booking0_.*
> from booking booking0_
> where booking0_.customer_id in (
> select customer1_.id
> from customer customer1_
> where lower((customer1_.first_name||'
> '||customer1_.last_name)) like '%gatef%'
> )
> order by booking0_.id desc
> limit 30;
>

It thinks it is going to find 30 rows which meet your condition very
quickly, so by walking the index backwards it can avoid needing to do a
sort. But, the rows which meet your sub-select conditions are biased
towards the front of the index, so in fact it was to walk backwards through
most of your index before finding 30 eligible rows.

Your best bet is probably to force it into the plan you want by using a CTE:

with t as
(select booking0_.*
from booking booking0_
where booking0_.customer_id in (
select customer1_.id
from customer customer1_
where lower((customer1_.first_name||'
'||customer1_.last_name)) like '%gatef%'
) select * from t order by booking0_.id desc limit 30;

Cheers,

Jeff

In response to

Responses

Browse pgsql-performance by date

  From Date Subject
Next Message domenico febbo 2016-11-14 17:36:51 Re: Some tuning suggestions on a Red Hat 6.7 - PG 9.5.3 production environment
Previous Message Seckin Pulatkan 2016-11-14 12:01:27 Query planner chooses index scan backward instead of better index option