Wrong results from self-join elimination with inheritance and ONLY

From: Tender Wang <tndrwang(at)gmail(dot)com>
To: PostgreSQL Hackers <pgsql-hackers(at)lists(dot)postgresql(dot)org>
Cc: Alexander Korotkov <aekorotkov(at)gmail(dot)com>
Subject: Wrong results from self-join elimination with inheritance and ONLY
Date: 2026-10-12 01:22:15
Message-ID: CAHewXNn4EjCQEvanN_FPKQ3OJWaBXq8Pxcj-DZYbeQ6_4xSFgw@mail.gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Hi,

I found a wrong-result case in self-join elimination involving an
inheritance scan and an ONLY scan.

Here is a reproducer:

CREATE TABLE r1 (id int, v int);
INSERT INTO r1 VALUES (1, 1);
CREATE TABLE r1c () INHERITS (r1);
INSERT INTO r1c VALUES (1, 100);
CREATE UNIQUE INDEX r1_id ON r1 (id);
ANALYZE r1, r1c;

SELECT * FROM r1 p1 JOIN ONLY r1 p2 ON p1.id = p2.id;

With enable_self_join_elimination enabled, this returns:

postgres=# show enable_self_join_elimination ;
enable_self_join_elimination
------------------------------
on
(1 row)

postgres=# SELECT * FROM r1 p1 JOIN ONLY r1 p2 ON p1.id = p2.id;
id | v | id | v
----+---+----+---
1 | 1 | 1 | 1
(1 row)

With it disabled, the query correctly returns:

postgres=# set enable_self_join_elimination = off;
SET
postgres=# SELECT * FROM r1 p1 JOIN ONLY r1 p2 ON p1.id = p2.id;
id | v | id | v
----+-----+----+---
1 | 1 | 1 | 1
1 | 100 | 1 | 1
(2 rows)

remove_self_joins_recurse() groups candidates by relation OID without
checking rte->inh.
In this case, the two references have the same OID but different scan scopes.
The unique index on r1 does not prove that a matching row from r1c is
the same physical row as the matching row in r1.

The attached patch excludes RTEs with inh set from SJE candidates.
Partitioned tables are already excluded by the relkind check, while
references to ordinary tables without children have their inh flag
cleared during preprocessing.

The patch also adds regression tests for both reference orders and
verifies that a join between two ONLY scans can still be eliminated.

--
Thanks,
Tender Wang

Attachment Content-Type Size
0001-Fix-self-join-elimination-for-inheritance-scans.patch text/plain 5.5 KB

Browse pgsql-hackers by date

  From Date Subject
Previous Message Richard Guo 2026-10-12 01:18:38 ERROR: failed to apply nullingrels to a non-Var