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 1tPkD3-00Eyom-J1 for pgsql-bugs@arkaria.postgresql.org; Mon, 23 Dec 2024 15:19:05 +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 1tPkD0-00BnM7-J4 for pgsql-bugs@arkaria.postgresql.org; Mon, 23 Dec 2024 15:19:02 +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 1tPkD0-00BnLz-9p for pgsql-bugs@lists.postgresql.org; Mon, 23 Dec 2024 15:19:02 +0000 Received: from sss.pgh.pa.us ([68.162.161.243]) by magus.postgresql.org with esmtps (TLS1.3) tls TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (Exim 4.94.2) (envelope-from ) id 1tPkCx-001EnL-4N for pgsql-bugs@lists.postgresql.org; Mon, 23 Dec 2024 15:19:01 +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 4BNFIuZC1347039; Mon, 23 Dec 2024 10:18:56 -0500 From: Tom Lane To: Kirill Reshke cc: pingw33n@gmail.com, pgsql-bugs@lists.postgresql.org Subject: Re: BUG #18751: Sub-optimal UNION ALL plan In-reply-to: References: <18751-887c7bf4e67e65a7@postgresql.org> Comments: In-reply-to Kirill Reshke message dated "Mon, 23 Dec 2024 19:24:40 +0500" MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-ID: <1347037.1734967136.1@sss.pgh.pa.us> Date: Mon, 23 Dec 2024 10:18:56 -0500 Message-ID: <1347038.1734967136@sss.pgh.pa.us> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Archived-At: Precedence: bulk Kirill Reshke writes: > I reproduced this on REL_16_STABLE, HEAD & REL_13_STABLE, so this is > not really a bug, just a missing optimization? Yeah. I believe what is happening is that the addition of the WHERE clause forces the second sub-SELECT to be planned as an independent query. And that level of planning has no idea that it might be useful to produce a result ordered by "t", so it doesn't generate a sub-plan that can do that. Then the best that the outer level can do is sort after-the-fact. You could work around this by writing the second sub-SELECT like (select * from t2 where ... order by t) regards, tom lane