Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1mQ9Dl-0003x4-HR for pgsql-performance@arkaria.postgresql.org; Tue, 14 Sep 2021 14:15:37 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.92) (envelope-from ) id 1mQ9Dk-00011g-Gs for pgsql-performance@arkaria.postgresql.org; Tue, 14 Sep 2021 14:15:36 +0000 Received: from magus.postgresql.org ([2a02:c0:301:0:ffff::29]) by malur.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1mQ9Dk-00011Y-8q for pgsql-performance@lists.postgresql.org; Tue, 14 Sep 2021 14:15:36 +0000 Received: from sss.pgh.pa.us ([66.207.139.130]) by magus.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1mQ9Di-0004Eo-4w for pgsql-performance@lists.postgresql.org; Tue, 14 Sep 2021 14:15:35 +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 18EEFUt9589351; Tue, 14 Sep 2021 10:15:30 -0400 From: Tom Lane To: Kristjan Mustkivi cc: Jeff Janes , Tomas Vondra , Pgsql Performance Subject: Re: Postgres chooses slow query plan from time to time In-reply-to: References: <31c01752-c4d6-7751-9d25-b1fac8f3a7aa@enterprisedb.com> Comments: In-reply-to Kristjan Mustkivi message dated "Tue, 14 Sep 2021 15:41:54 +0300" MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-ID: <589349.1631628930.1@sss.pgh.pa.us> Date: Tue, 14 Sep 2021 10:15:30 -0400 Message-ID: <589350.1631628930@sss.pgh.pa.us> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Archived-At: Precedence: bulk Kristjan Mustkivi writes: > -> Index Scan Backward using player_balance_history_idx2 on > mytable pbh (cost=0.70..21639.94 rows=3885 width=66) (actual > time=5934.153..5934.153 rows=1 loops=1) > Index Cond: ((cage_code = $3) AND (cage_player_id = > $2) AND (modified_time < $5)) > Filter: (((product_code)::text = ($1)::text) AND > ((balance_type)::text = ($4)::text)) > Rows Removed by Filter: 95589 > Buffers: shared hit=7623 read=18217 So indeed, the core issue is that that filter condition is very selective, and applying it after the index scan is expensive. Perhaps it would help to create an index that includes those columns along with cage_code and cage_player_id. (It's not clear whether to bother with modified_time in this specialized index, but if you do include it, it needs to be the last column since you're putting a non-equality condition on it.) regards, tom lane