Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.3) tls TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (Exim 4.94.2) (envelope-from ) id 1qPSvr-00B6aq-RR for pgsql-bugs@arkaria.postgresql.org; Fri, 28 Jul 2023 19:15:23 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.94.2) (envelope-from ) id 1qPSvp-000Wg1-K7 for pgsql-bugs@arkaria.postgresql.org; Fri, 28 Jul 2023 19:15:21 +0000 Received: from magus.postgresql.org ([2a02:c0:301:0:ffff::29]) by malur.postgresql.org with esmtps (TLS1.3) tls TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (Exim 4.94.2) (envelope-from ) id 1qPSvp-000Wer-Bb for pgsql-bugs@lists.postgresql.org; Fri, 28 Jul 2023 19:15:21 +0000 Received: from sss.pgh.pa.us ([66.207.139.130]) by magus.postgresql.org with esmtps (TLS1.3) tls TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (Exim 4.94.2) (envelope-from ) id 1qPSvm-000vv5-RW for pgsql-bugs@lists.postgresql.org; Fri, 28 Jul 2023 19:15:20 +0000 Received: from sss1.sss.pgh.pa.us (localhost [127.0.0.1]) by sss.pgh.pa.us (8.15.2/8.15.2) with ESMTP id 36SJFF8u2373033; Fri, 28 Jul 2023 15:15:15 -0400 From: Tom Lane To: christian.vallieres@evimbec.ca cc: pgsql-bugs@lists.postgresql.org Subject: Re: BUG #18042: Query planner favor index corresponding to a order by with a limit even when there is a where In-reply-to: <18042-27d35e97efb1583f@postgresql.org> References: <18042-27d35e97efb1583f@postgresql.org> Comments: In-reply-to PG Bug reporting form message dated "Fri, 28 Jul 2023 18:40:43 -0000" MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-ID: <2373031.1690571715.1@sss.pgh.pa.us> Date: Fri, 28 Jul 2023 15:15:15 -0400 Message-ID: <2373032.1690571715@sss.pgh.pa.us> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Archived-At: Precedence: bulk PG Bug reporting form 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