From 63977351de2c7978c1b271a3aa075ab204504aa3 Mon Sep 17 00:00:00 2001 From: Richard Guo Date: Wed, 18 Nov 2026 18:13:35 +0900 Subject: [PATCH v7 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. Since those relations now keep their UniqueKeys, a join relation within the right-hand side can be proven distinct as well. 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 | 200 +++++++++++++++++++++++ src/test/regress/sql/uniquekeys.sql | 44 +++++ 5 files changed, 327 insertions(+), 15 deletions(-) diff --git a/src/backend/optimizer/README b/src/backend/optimizer/README index e22225e131e..f738ce14e47 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 8750aea0125..4e2c8deafb6 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 void get_left_join_ecs(PlannerInfo *root, RelOptInfo *joinrel, List **min_lefthands, List **ecs); static void add_left_join_ec(PlannerInfo *root, RelOptInfo *joinrel, @@ -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); } /* @@ -204,6 +217,11 @@ rel_is_distinct_for_pathkeys(PlannerInfo *root, RelOptInfo *rel, * to the set when the join's left-hand relations are all accounted for (see * get_left_join_ecs). * + * 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 @@ -212,11 +230,15 @@ joinrel_is_distinct_for_ecs(PlannerInfo *root, RelOptInfo *joinrel, { Bitmapset *joined_ecs = NULL; Relids full_join_relids = NULL; + Relids rhs_relids; Relids remaining; List *left_join_lefthands; List *left_join_ecs; bool found; + if (!get_semijoin_rhs_relids(root, joinrel, &rhs_relids)) + return false; + /* Find the nullable-side ECs of the left joins within this join rel */ get_left_join_ecs(root, joinrel, &left_join_lefthands, &left_join_ecs); @@ -244,8 +266,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 { @@ -286,6 +312,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 @@ -448,17 +514,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 7b3d89e50f7..efff5bddda8 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 ee47bc1b50a..4f392ba3b6e 100644 --- a/src/test/regress/expected/uniquekeys.out +++ b/src/test/regress/expected/uniquekeys.out @@ -199,8 +199,165 @@ 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) + +-- a join relation within the right-hand side can still be proven unique +explain (verbose, costs off) +select * from uk_a a where exists + (select 1 from uk_b b left join (uk_c c join uk_d d on c.x = d.a and c.y = d.b) + on b.x = c.id where b.y = a.y); + QUERY PLAN +-------------------------------------------------------------------------------- + Nested Loop + Output: a.id, a.x, a.y + Inner Unique: true + Join Filter: (a.y = b.y) + -> Seq Scan on public.uk_a a + Output: a.id, a.x, a.y + -> Materialize + Output: b.y + -> HashAggregate + Output: b.y + Group Key: b.y + -> Nested Loop Left Join + Output: b.y + Inner Unique: true + -> Seq Scan on public.uk_b b + Output: b.id, b.x, b.y + -> Nested Loop + Output: c.id + Inner Unique: true + -> Index Scan using uk_c_pkey on public.uk_c c + Output: c.id, c.x, c.y + Index Cond: (c.id = b.x) + -> Index Only Scan using uk_d_pkey on public.uk_d d + Output: d.a, d.b + Index Cond: ((d.a = c.x) AND (d.b = c.y)) +(25 rows) + reset enable_hashjoin; reset enable_mergejoin; +-- A join relation that has the right-hand side of a semijoin but only part of +-- its left-hand side is not handled. Here the join of uk_b and the +-- unique-ified uk_d can have several rows for a row of uk_c. +explain (verbose, costs off) +select * from uk_a a, uk_b b, uk_c c +where b.id = 1 and + (b.x, c.x, a.y) in (select d.x, d.a, d.a + d.b from uk_d d); + QUERY PLAN +--------------------------------------------------------------------------------- + Hash Join + Output: a.id, a.x, a.y, b.id, b.x, b.y, c.id, c.x, c.y + Hash Cond: (a.y = (d.a + d.b)) + -> Seq Scan on public.uk_a a + Output: a.id, a.x, a.y + -> Hash + Output: b.id, b.x, b.y, d.a, d.b, c.id, c.x, c.y + -> Hash Join + Output: b.id, b.x, b.y, d.a, d.b, c.id, c.x, c.y + Hash Cond: (c.x = d.a) + -> Seq Scan on public.uk_c c + Output: c.id, c.x, c.y + -> Hash + Output: b.id, b.x, b.y, d.a, d.b + -> Hash Join + Output: b.id, b.x, b.y, d.a, d.b + Inner Unique: true + Hash Cond: (d.x = b.x) + -> HashAggregate + Output: d.x, d.a, d.b + Group Key: d.x, d.a, (d.a + d.b) + -> Seq Scan on public.uk_d d + Output: d.x, d.a, d.b, (d.a + d.b) + -> Hash + Output: b.id, b.x, b.y + -> Index Scan using uk_b_pkey on public.uk_b b + Output: b.id, b.x, b.y + Index Cond: (b.id = 1) +(28 rows) + -- A clause on a column that is nulled by an outer join works like one on the -- column itself. The join of interest is put under a full join, because a -- left join's clause would let the planner reduce the outer join below it. @@ -620,6 +777,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 2ef839a8001..abbebefcae1 100644 --- a/src/test/regress/sql/uniquekeys.sql +++ b/src/test/regress/sql/uniquekeys.sql @@ -63,9 +63,40 @@ 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; + +-- a join relation within the right-hand side can still be proven unique +explain (verbose, costs off) +select * from uk_a a where exists + (select 1 from uk_b b left join (uk_c c join uk_d d on c.x = d.a and c.y = d.b) + on b.x = c.id where b.y = a.y); + reset enable_hashjoin; reset enable_mergejoin; +-- A join relation that has the right-hand side of a semijoin but only part of +-- its left-hand side is not handled. Here the join of uk_b and the +-- unique-ified uk_d can have several rows for a row of uk_c. +explain (verbose, costs off) +select * from uk_a a, uk_b b, uk_c c +where b.id = 1 and + (b.x, c.x, a.y) in (select d.x, d.a, d.a + d.b from uk_d d); + -- A clause on a column that is nulled by an outer join works like one on the -- column itself. The join of interest is put under a full join, because a -- left join's clause would let the planner reduce the outer join below it. @@ -184,6 +215,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.54.0 (Apple Git-157)