Re: BUG #18042: Query planner favor index corresponding to a order by with a limit even when there is a where

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: christian(dot)vallieres(at)evimbec(dot)ca
Cc: pgsql-bugs(at)lists(dot)postgresql(dot)org
Subject: Re: BUG #18042: Query planner favor index corresponding to a order by with a limit even when there is a where
Date: 2023-07-28 19:15:15
Message-ID: 2373032.1690571715@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-bugs

PG Bug reporting form <noreply(at)postgresql(dot)org> writes:
> Query planner favor starting with the event table and use the 102MB
> event_date_idx corresponding to a order by with a limit,
> instead of the 94MB event_event_type_id_idx corresponding to the where
> condition.

Sadly, this isn't something we can do much about. Estimating the
behavior of a query with ORDER BY and a small LIMIT is simply very
tricky: a plan that depends on an indexscan stopping early might
be very fast, or it might not be, depending on factors such as row
physical locations that the planner doesn't have a lot of info about.

Your best bet might be to prevent event_date_idx from matching the
query's sort order. Seeing that date is NOT NULL, I'd suggest
changing either the index or the query (not both!) to specify NULLS
FIRST. This'll make no actual difference given the lack of nulls, but
the planner isn't cognizant of that and will decide it can't use the
index in this way for this query.

regards, tom lane

In response to

Browse pgsql-bugs by date

  From Date Subject
Next Message Jeff Janes 2023-07-28 21:02:15 Re: BUG #18042: Query planner favor index corresponding to a order by with a limit even when there is a where
Previous Message PG Bug reporting form 2023-07-28 18:40:43 BUG #18042: Query planner favor index corresponding to a order by with a limit even when there is a where