From 77d08148408ba3c3c66c2cc45704193c17238dcc Mon Sep 17 00:00:00 2001 From: Richard Guo Date: Wed, 18 Nov 2026 18:13:35 +0900 Subject: [PATCH v6 5/8] Teach UniqueKeys about semijoins and antijoins So far a join relation that involved a semijoin or an antijoin could not be proven distinct, because the relations on the right-hand side of such joins were treated as having no UniqueKeys. But a semijoin or antijoin emits each row of its left-hand side at most once, whatever its right-hand side holds. So the relations on the right-hand side of such a join performed within a join relation need neither UniqueKeys nor to be shown to have only one possible row. This commit leaves them out of the relations to account for. The one case not handled is a join relation that includes the right-hand side of a semijoin but only part of its left-hand side, which can only be formed by making the right-hand side unique first. --- src/backend/optimizer/README | 13 ++- src/backend/optimizer/path/uniquekeys.c | 83 ++++++++++++--- src/include/nodes/pathnodes.h | 2 +- src/test/regress/expected/uniquekeys.out | 127 +++++++++++++++++++++++ src/test/regress/sql/uniquekeys.sql | 30 ++++++ 5 files changed, 240 insertions(+), 15 deletions(-) diff --git a/src/backend/optimizer/README b/src/backend/optimizer/README index 728620bdb08..2d90f230eca 100644 --- a/src/backend/optimizer/README +++ b/src/backend/optimizer/README @@ -1048,8 +1048,8 @@ so that a query that never needs them does not pay for them. UniqueKeys are used to detect unique inner sides of joins when the inner side is itself a join, and to skip DISTINCT and GROUP BY steps whose input is already distinct. The following describes each of these in turn, and -then how outer joins fit in. For now only plain tables get UniqueKeys, and -only joins that involve no semijoins or antijoins are handled. +then how outer joins and semijoins fit in. For now only plain tables get +UniqueKeys. We do not keep UniqueKeys for join relations. A join relation would typically have many of them, most of which would never be used. And since @@ -1174,6 +1174,15 @@ column of the relation that cannot be NULL, due to a NOT NULL constraint or a strict restriction clause. Such a column is NULL in the join's output only when the relation is null-extended, which tells the two cases apart. +Semijoins and antijoins are simple: such a join emits each row of its +left-hand side at most once, whatever its right-hand side holds. So the +relations on the right-hand side of a semijoin or antijoin performed within +the join relation need not be shown to have only one possible row, nor do +they need UniqueKeys at all. The one case we do not try to handle is a +join relation that includes the right-hand side of a semijoin but only part +of its left-hand side, which can only be formed by making the right-hand +side unique first. + Order of processing for EquivalenceClasses and PathKeys ------------------------------------------------------- diff --git a/src/backend/optimizer/path/uniquekeys.c b/src/backend/optimizer/path/uniquekeys.c index 1ec7b469dd2..fc76dc6f959 100644 --- a/src/backend/optimizer/path/uniquekeys.c +++ b/src/backend/optimizer/path/uniquekeys.c @@ -45,6 +45,8 @@ static bool joinrel_is_distinct_for_ecs(PlannerInfo *root, RelOptInfo *joinrel, Bitmapset *known_ecs, bool nulls_equal); +static bool get_semijoin_rhs_relids(PlannerInfo *root, RelOptInfo *joinrel, + Relids *rhs_relids); static Bitmapset *get_left_join_ecs(PlannerInfo *root, RelOptInfo *joinrel); static Bitmapset *get_joined_ecs(PlannerInfo *root, RelOptInfo *joinrel, Bitmapset *left_join_ecs); @@ -82,6 +84,8 @@ static Bitmapset *get_own_eclass_indexes(PlannerInfo *root, RelOptInfo *rel); bool joinrel_supports_distinctness(PlannerInfo *root, RelOptInfo *joinrel) { + Relids rhs_relids; + Assert(IS_JOIN_REL(joinrel)); /* A grouped join rel's rows are not combinations of base rel rows */ @@ -90,8 +94,17 @@ joinrel_supports_distinctness(PlannerInfo *root, RelOptInfo *joinrel) build_base_rel_uniquekeys(root); - /* Every base rel in the join must have a UniqueKey */ - return !bms_overlap(joinrel->relids, root->no_uniquekey_relids); + /* If every base rel in the join has a UniqueKey, we can go ahead */ + if (!bms_overlap(joinrel->relids, root->no_uniquekey_relids)) + return true; + + /* Otherwise, those that don't must not need one */ + if (!get_semijoin_rhs_relids(root, joinrel, &rhs_relids)) + return false; + + return bms_is_subset(bms_intersect(joinrel->relids, + root->no_uniquekey_relids), + rhs_relids); } /* @@ -200,6 +213,11 @@ rel_is_distinct_for_pathkeys(PlannerInfo *root, RelOptInfo *rel, * the left-hand rels must still be fixed by other means: no EC has un-nulled * members on both sides of a left join. * + * A semijoin or antijoin emits each row of its left-hand side at most once, + * whatever its right-hand side holds. So the relations on the right-hand + * side of such a join performed within the join relation need not be + * accounted for. They are found by get_semijoin_rhs_relids. + * * The caller must have checked joinrel_supports_distinctness(). */ static bool @@ -209,9 +227,13 @@ joinrel_is_distinct_for_ecs(PlannerInfo *root, RelOptInfo *joinrel, Bitmapset *left_join_ecs; Bitmapset *joined_ecs = NULL; Relids full_join_relids = NULL; + Relids rhs_relids; Relids remaining; bool found; + if (!get_semijoin_rhs_relids(root, joinrel, &rhs_relids)) + return false; + left_join_ecs = get_left_join_ecs(root, joinrel); known_ecs = bms_add_members(known_ecs, left_join_ecs); @@ -239,8 +261,12 @@ joinrel_is_distinct_for_ecs(PlannerInfo *root, RelOptInfo *joinrel, } } - /* The relids of outer joins are not relations to account for */ + /* + * The relids of outer joins are not relations to account for, and neither + * are the right-hand relations of semijoins and antijoins. + */ remaining = bms_difference(joinrel->relids, root->outer_join_rels); + remaining = bms_del_members(remaining, rhs_relids); do { @@ -272,6 +298,46 @@ joinrel_is_distinct_for_ecs(PlannerInfo *root, RelOptInfo *joinrel, return remaining == NULL; } +/* + * get_semijoin_rhs_relids + * Find the relations that are on the right-hand side of a semijoin or + * antijoin performed within the join relation. + * + * The relids are returned in *rhs_relids. Returns false if the join + * relation is one that we cannot reason about: that is the case if it + * includes the right-hand side of a semijoin but only part of its left-hand + * side, which means the right-hand side has been unique-ified. + */ +static bool +get_semijoin_rhs_relids(PlannerInfo *root, RelOptInfo *joinrel, + Relids *rhs_relids) +{ + *rhs_relids = NULL; + + foreach_node(SpecialJoinInfo, sjinfo, root->join_info_list) + { + if (sjinfo->jointype != JOIN_SEMI && sjinfo->jointype != JOIN_ANTI) + continue; + + /* + * The join is of no concern if the join relation has nothing of its + * right-hand side, or lies entirely within its right-hand side. + */ + if (!bms_overlap(sjinfo->syn_righthand, joinrel->relids) || + bms_is_subset(joinrel->relids, sjinfo->syn_righthand)) + continue; + + /* Otherwise the whole join must be performed within the relation */ + if (!bms_is_subset(sjinfo->syn_righthand, joinrel->relids) || + !bms_is_subset(sjinfo->min_lefthand, joinrel->relids)) + return false; + + *rhs_relids = bms_add_members(*rhs_relids, sjinfo->syn_righthand); + } + + return true; +} + /* * get_left_join_ecs * Get the indexes of the ECs on the nullable side of the mergejoinable @@ -414,17 +480,10 @@ build_base_rel_uniquekeys(PlannerInfo *root) if (root->outer_join_rels != NULL) build_base_eclasses(root); - /* - * We don't handle semijoins and antijoins. Rather than checking for them - * in each join relation, treat their right-hand relations as having no - * UniqueKeys. Also note the full joins, for use below. - */ + /* Note the full joins, for use below */ foreach_node(SpecialJoinInfo, sjinfo, root->join_info_list) { - if (sjinfo->jointype == JOIN_SEMI || sjinfo->jointype == JOIN_ANTI) - no_uniquekey_relids = bms_add_members(no_uniquekey_relids, - sjinfo->syn_righthand); - else if (sjinfo->jointype == JOIN_FULL) + if (sjinfo->jointype == JOIN_FULL) full_join_relids = bms_add_member(full_join_relids, sjinfo->ojrelid); } diff --git a/src/include/nodes/pathnodes.h b/src/include/nodes/pathnodes.h index 8d0b84514a1..3a9e9352021 100644 --- a/src/include/nodes/pathnodes.h +++ b/src/include/nodes/pathnodes.h @@ -441,7 +441,7 @@ struct PlannerInfo /* set true once the base relations' UniqueKeys have been built */ bool uniquekeys_built; - /* base relations that keep a join relation from being proven distinct */ + /* base relations that have no UniqueKeys */ Relids no_uniquekey_relids; /* list of "canonical" PathKeys */ diff --git a/src/test/regress/expected/uniquekeys.out b/src/test/regress/expected/uniquekeys.out index f21a54cb892..a2b45c7add6 100644 --- a/src/test/regress/expected/uniquekeys.out +++ b/src/test/regress/expected/uniquekeys.out @@ -199,6 +199,90 @@ select * from uk_a a left join (12 rows) reset join_collapse_limit; +-- the right-hand side of a semijoin or antijoin need not be unique +explain (verbose, costs off) +select * from uk_a a left join + (select * from uk_b b + where exists (select 1 from uk_c c where c.x = b.x)) s on a.x = s.id; + QUERY PLAN +--------------------------------------------------------------- + Nested Loop Left Join + Output: a.id, a.x, a.y, b.id, b.x, b.y + Inner Unique: true + Join Filter: (a.x = b.id) + -> Seq Scan on public.uk_a a + Output: a.id, a.x, a.y + -> Materialize + Output: b.id, b.x, b.y + -> Nested Loop + Output: b.id, b.x, b.y + Inner Unique: true + Join Filter: (b.x = c.x) + -> Index Scan using uk_b_pkey on public.uk_b b + Output: b.id, b.x, b.y + -> Materialize + Output: c.x + -> HashAggregate + Output: c.x + Group Key: c.x + -> Seq Scan on public.uk_c c + Output: c.id, c.x, c.y +(21 rows) + +explain (verbose, costs off) +select * from uk_a a left join + (select * from uk_b b + where not exists (select 1 from uk_c c where c.x = b.x)) s on a.x = s.id; + QUERY PLAN +--------------------------------------------------- + Nested Loop Left Join + Output: a.id, a.x, a.y, b.id, b.x, b.y + Inner Unique: true + Join Filter: (a.x = b.id) + -> Seq Scan on public.uk_a a + Output: a.id, a.x, a.y + -> Materialize + Output: b.id, b.x, b.y + -> Nested Loop Anti Join + Output: b.id, b.x, b.y + Join Filter: (c.x = b.x) + -> Seq Scan on public.uk_b b + Output: b.id, b.x, b.y + -> Materialize + Output: c.x + -> Seq Scan on public.uk_c c + Output: c.x +(17 rows) + +-- but its left-hand side must be +explain (verbose, costs off) +select * from uk_a a left join + (select * from uk_b b + where exists (select 1 from uk_c c where c.x = b.x)) s on a.x = s.x; + QUERY PLAN +--------------------------------------------------------- + Nested Loop Left Join + Output: a.id, a.x, a.y, b.id, b.x, b.y + Join Filter: (a.x = b.x) + -> Seq Scan on public.uk_a a + Output: a.id, a.x, a.y + -> Materialize + Output: b.id, b.x, b.y + -> Nested Loop + Output: b.id, b.x, b.y + Inner Unique: true + Join Filter: (b.x = c.x) + -> Seq Scan on public.uk_b b + Output: b.id, b.x, b.y + -> Materialize + Output: c.x + -> HashAggregate + Output: c.x + Group Key: c.x + -> Seq Scan on public.uk_c c + Output: c.id, c.x, c.y +(20 rows) + reset enable_hashjoin; reset enable_mergejoin; -- A clause on a column that is nulled by an outer join works like one on the @@ -619,6 +703,49 @@ from (select * from uk_n where v > 0) n1 full join Index Cond: (v > 0) (11 rows) +-- semijoins and antijoins +explain (costs off) +select distinct b.id from uk_b b +where exists (select 1 from uk_c c where c.x = b.x); + QUERY PLAN +-------------------------------------- + Hash Join + Hash Cond: (b.x = c.x) + -> Seq Scan on uk_b b + -> Hash + -> HashAggregate + Group Key: c.x + -> Seq Scan on uk_c c +(7 rows) + +explain (costs off) +select distinct b.id from uk_b b +where not exists (select 1 from uk_c c where c.x = b.x); + QUERY PLAN +-------------------------------- + Hash Anti Join + Hash Cond: (b.x = c.x) + -> Seq Scan on uk_b b + -> Hash + -> Seq Scan on uk_c c +(5 rows) + +explain (costs off) +select distinct b.x from uk_b b +where exists (select 1 from uk_c c where c.x = b.x); + QUERY PLAN +-------------------------------------------- + HashAggregate + Group Key: b.x + -> Hash Join + Hash Cond: (b.x = c.x) + -> Seq Scan on uk_b b + -> Hash + -> HashAggregate + Group Key: c.x + -> Seq Scan on uk_c c +(9 rows) + -- GROUP BY without aggregates is handled likewise explain (costs off) select a.id, a.y from uk_a a join uk_b b on a.x = b.id group by a.id, a.y; diff --git a/src/test/regress/sql/uniquekeys.sql b/src/test/regress/sql/uniquekeys.sql index 106a1c35b32..7465e8ff424 100644 --- a/src/test/regress/sql/uniquekeys.sql +++ b/src/test/regress/sql/uniquekeys.sql @@ -63,6 +63,23 @@ select * from uk_a a left join reset join_collapse_limit; +-- the right-hand side of a semijoin or antijoin need not be unique +explain (verbose, costs off) +select * from uk_a a left join + (select * from uk_b b + where exists (select 1 from uk_c c where c.x = b.x)) s on a.x = s.id; + +explain (verbose, costs off) +select * from uk_a a left join + (select * from uk_b b + where not exists (select 1 from uk_c c where c.x = b.x)) s on a.x = s.id; + +-- but its left-hand side must be +explain (verbose, costs off) +select * from uk_a a left join + (select * from uk_b b + where exists (select 1 from uk_c c where c.x = b.x)) s on a.x = s.x; + reset enable_hashjoin; reset enable_mergejoin; @@ -183,6 +200,19 @@ select distinct n1.v, n2.v from (select * from uk_n where v > 0) n1 full join (select * from uk_n where v > 0) n2 on n1.w = n2.w; +-- semijoins and antijoins +explain (costs off) +select distinct b.id from uk_b b +where exists (select 1 from uk_c c where c.x = b.x); + +explain (costs off) +select distinct b.id from uk_b b +where not exists (select 1 from uk_c c where c.x = b.x); + +explain (costs off) +select distinct b.x from uk_b b +where exists (select 1 from uk_c c where c.x = b.x); + -- GROUP BY without aggregates is handled likewise explain (costs off) select a.id, a.y from uk_a a join uk_b b on a.x = b.id group by a.id, a.y; -- 2.53.0