Removed left join leaves its key in the outer rel's target list

From: hi(at)joel(dot)id
To: pgsql-bugs(at)lists(dot)postgresql(dot)org
Subject: Removed left join leaves its key in the outer rel's target list
Date: 2026-11-29 07:55:40
Message-ID: xuMg6nUAJWsPto-7JaWJ4GwHJEMSYISakvZH4Tv2JBLdDw3z675CTl_POT2HcF-CYwY19H0VD1x7ioH2vKzg5N1yXkELIRb-ES3yrjY3YaA=@joel.id
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-bugs

Hi,

On PostgreSQL 18.6, when a left join is removed because nothing reads its
inner side, the outer relation's scan still emits the join key. Where that
scan feeds another join, the dead column rides along: under a hash join it
widens the hash table, which can make it spill.

Reproducer (temporary tables only):

CREATE TEMP TABLE q (s bigint, p bigint, base int);
CREATE TEMP TABLE n (id bigint PRIMARY KEY, kind text, label text);
INSERT INTO q SELECT i, i % 100, 1 FROM generate_series(1, 100000) i;
INSERT INTO n SELECT i, 'a', 'p' || i FROM generate_series(0, 99) i;
ANALYZE q; ANALYZE n;

EXPLAIN (VERBOSE, COSTS OFF)
SELECT count(*)
FROM q q1 LEFT JOIN n n1 ON n1.id = q1.p AND n1.kind IN ('a', 'b')
JOIN (q q2 LEFT JOIN n n2 ON n2.id = q2.p AND n2.kind IN ('a', 'b'))
ON q1.s = q2.s;

Aggregate
Output: count(*)
-> Hash Join
Hash Cond: (q1.s = q2.s)
-> Seq Scan on pg_temp.q q1
Output: q1.s, q1.p, q1.base
-> Hash
Output: q2.s, q2.p
-> Seq Scan on pg_temp.q q2
Output: q2.s, q2.p

Both left joins are removed, but the Hash still carries q2.p, which only
the removed join clause n2.id = q2.p read. Without the left joins,

EXPLAIN (VERBOSE, COSTS OFF)
SELECT count(*) FROM q q1 JOIN q q2 ON q1.s = q2.s;

the Hash's output is q2.s alone.

As far as I can see, remove_rel_from_query() in
src/backend/optimizer/plan/analyzejoins.c recomputes attr_needed for the
remaining base rels, but the Vars build_base_rel_tlists() put in their
reltarget before join removal stay there, needed or not.

Answers are correct; the cost is width. In our application the same shape
comes from an inlined SQL function whose view left-joins a label table on
an id, joined with itself on another column: one hash join went from 84 ms
to 100 ms because the wider hash table spilled into 4 batches. I have not
checked master.

PostgreSQL 18.6 on aarch64-unknown-linux-gnu, compiled by gcc (Ubuntu
13.3.0-6ubuntu2~24.04.1) 13.3.0, 64-bit

Thanks

Responses

Browse pgsql-bugs by date

  From Date Subject
Next Message PG Bug reporting form 2026-11-29 09:08:32 BUG #19955: Parallel Hash doubles nbatch without limit under build-side skew; backend OOM-killed
Previous Message Tender Wang 2026-11-29 06:16:27 Re: BUG #19804: "variable not found in subplan target list", DISTINCT agg over Gather`