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 1lt9gk-00021a-AQ for pgsql-bugs@arkaria.postgresql.org; Tue, 15 Jun 2021 14:05:10 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.92) (envelope-from ) id 1lt9gj-0004PN-9t for pgsql-bugs@arkaria.postgresql.org; Tue, 15 Jun 2021 14:05:09 +0000 Received: from makus.postgresql.org ([2001:4800:3e1:1::229]) by malur.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1lt9gj-0004Ot-35 for pgsql-bugs@lists.postgresql.org; Tue, 15 Jun 2021 14:05:09 +0000 Received: from sss.pgh.pa.us ([66.207.139.130]) by makus.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1lt9gd-00043X-Br for pgsql-bugs@lists.postgresql.org; Tue, 15 Jun 2021 14:05:08 +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 15FE52Yf355907; Tue, 15 Jun 2021 10:05:02 -0400 From: Tom Lane To: Floris Van Nee cc: "pgsql-bugs@lists.postgresql.org" Subject: Re: Postgres turns LEFT JOIN into INNER JOIN - incorrect results In-reply-to: References: Comments: In-reply-to Floris Van Nee message dated "Tue, 15 Jun 2021 13:06:27 -0000" MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-ID: <355905.1623765902.1@sss.pgh.pa.us> Content-Transfer-Encoding: quoted-printable Date: Tue, 15 Jun 2021 10:05:02 -0400 Message-ID: <355906.1623765902@sss.pgh.pa.us> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Archived-At: Precedence: bulk Floris Van Nee writes: > We've ran into a situation in which Postgres returns an incorrect query = result. I've managed to narrow it down to the following reproducible examp= le. I've encountered it on 12.4, but it reproduces on HEAD. I don't think this is incorrect. I was stumped at first too, but then I tried changing this: > CREATE OR REPLACE FUNCTION test_internal(_a text) > RETURNS TABLE(_a text) to CREATE OR REPLACE FUNCTION test_internal(_a text) RETURNS TABLE(__a text) and the issue went away. After that it became pretty clear what is happening: in > CREATE OR REPLACE FUNCTION test(_a text) > RETURNS TABLE(a text) > LANGUAGE sql > STABLE PARALLEL SAFE ROWS 1 > AS $function$ > SELECT > t2.a > FROM (VALUES ('a')) t2(a) > LEFT JOIN test_internal(_a) t1 ON TRUE > WHERE t2.a =3D _a > $function$ > ; the unqualified "_a" in the WHERE clause is taken to refer to the output column of "test_internal(_a) t1", not the outer function's parameter as you're supposing. Given that interpretation, it's valid to strength-reduce the join. Short answer: too many "_a"s. regards, tom lane