From b0ab1c9e2079186d6a1e82cda3c366de420fe1f7 Mon Sep 17 00:00:00 2001 From: Richard Guo Date: Fri, 20 Nov 2026 14:17:58 +0900 Subject: [PATCH v6 8/8] Build UniqueKeys for subquery relations A subquery that cannot be flattened into the parent query is a base relation of that query. So far only plain tables had UniqueKeys, so a join relation that contained such a subquery could never be proven distinct, and neither could the result of a query that selects from one. This commit builds UniqueKeys for a subquery that is distinct by construction, through DISTINCT, GROUP BY, a set operation, or by returning at most one row. The rules are those of query_is_distinct_for, which already serves the case where a subquery is the inner side of a join by itself. A UniqueKey is made of the EquivalenceClasses of the output columns that the subquery is distinct on, in the same way as one is made of the EquivalenceClasses of the columns of a unique index. Those constructs consider NULLs equal to each other, so these UniqueKeys are marked null_aware. A relation with LATERAL references is scanned anew for each row of the relations it refers to, and its UniqueKeys hold only within one scan. So such a relation is accounted for only after the relations it refers to. We do not look into a subquery to find which of its output columns cannot be NULL, so a subquery that is nulled by a full join cannot be accounted for when NULLs are considered equal. A subquery that is distinct only because of the relations it is made of is not handled. --- src/backend/optimizer/README | 13 +- src/backend/optimizer/path/uniquekeys.c | 149 ++++++++++++++++++++++- src/test/regress/expected/uniquekeys.out | 132 ++++++++++++++++++++ src/test/regress/sql/uniquekeys.sql | 33 +++++ 4 files changed, 322 insertions(+), 5 deletions(-) diff --git a/src/backend/optimizer/README b/src/backend/optimizer/README index ac3b1743aec..479a60a9ada 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, semijoins and other kinds of relations fit in. For -now only plain tables get UniqueKeys. +then how outer joins, semijoins, subqueries and other kinds of relations +fit in. 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 @@ -1183,6 +1183,15 @@ 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. +A subquery that could not be flattened into the query is a base relation +too, and gets UniqueKeys if it is distinct by construction, through +DISTINCT, GROUP BY, a set operation and so on. A UniqueKey then consists +of the ECs of the output columns in question. Since those constructs +consider NULLs equal, such UniqueKeys are marked null_aware. A relation +with LATERAL references is scanned anew for each row of the relations it +refers to, and its UniqueKeys hold only within one scan, so those relations +have to be shown to have only one possible row first. + Appendrel children have no UniqueKeys. A child relation that is by itself the inner side of a join is checked through its own unique indexes, like any plain relation. For a child join we rely on its parent: the rows of a diff --git a/src/backend/optimizer/path/uniquekeys.c b/src/backend/optimizer/path/uniquekeys.c index 08ab6d7e7de..f2d45a6a783 100644 --- a/src/backend/optimizer/path/uniquekeys.c +++ b/src/backend/optimizer/path/uniquekeys.c @@ -4,8 +4,9 @@ * Utilities for proving relations distinct using UniqueKeys * * A UniqueKey is a set of EquivalenceClasses that no two rows of a base - * relation agree on. Plain relations get them from their unique indexes. - * Join relations have no UniqueKeys of their own: whether a join relation is + * relation agree on. Plain relations get them from their unique indexes, + * and subquery relations from what makes the subquery distinct. Join + * relations have no UniqueKeys of their own: whether a join relation is * distinct is worked out when needed, from the UniqueKeys of the base * relations it consists of. Appendrel children and relations that are * partially aggregated by eager aggregation have none either; see @@ -36,12 +37,15 @@ #include "postgres.h" #include "access/sysattr.h" +#include "nodes/makefuncs.h" #include "nodes/multibitmapset.h" +#include "nodes/nodeFuncs.h" #include "optimizer/clauses.h" #include "optimizer/optimizer.h" #include "optimizer/pathnode.h" #include "optimizer/paths.h" #include "optimizer/tlist.h" +#include "parser/parse_agg.h" #include "rewrite/rewriteManip.h" #include "utils/lsyscache.h" @@ -56,6 +60,10 @@ static Bitmapset *get_joined_ecs(PlannerInfo *root, RelOptInfo *joinrel, static void build_base_rel_uniquekeys(PlannerInfo *root); static void build_base_eclasses(PlannerInfo *root); static void build_plain_rel_uniquekeys(PlannerInfo *root, RelOptInfo *rel); +static void build_subquery_rel_uniquekeys(PlannerInfo *root, RelOptInfo *rel); +static void add_subquery_uniquekey(PlannerInfo *root, RelOptInfo *rel, + List *sgc_tlist, List *out_tlist, + List *clauses); static void build_notnull_eclass_indexes(PlannerInfo *root, RelOptInfo *rel); static void add_uniquekey(RelOptInfo *rel, Bitmapset *eclass_indexes, bool null_aware); @@ -389,6 +397,14 @@ joinrel_is_distinct_for_ecs(PlannerInfo *root, RelOptInfo *joinrel, nulls_equal)) continue; + /* + * A relation with lateral references is scanned anew for each row + * of the relations it refers to, and its UniqueKeys hold only + * within one scan. So those relations have to come first. + */ + if (bms_overlap(rel->lateral_relids, remaining)) + continue; + if (!rel_has_uniquekey_in(root, rel, known_ecs, joined_ecs, nulls_equal)) continue; @@ -601,7 +617,7 @@ build_base_rel_uniquekeys(PlannerInfo *root) if (rel == NULL) continue; - /* Currently we only know about plain relations */ + /* Currently we only know about plain relations ... */ if (rel->reloptkind == RELOPT_BASEREL && rel->rtekind == RTE_RELATION) { @@ -613,6 +629,12 @@ build_base_rel_uniquekeys(PlannerInfo *root) build_notnull_eclass_indexes(root, rel); } + /* ... and subqueries, though not the parents of appendrels */ + if (rel->reloptkind == RELOPT_BASEREL && + rel->rtekind == RTE_SUBQUERY && + !root->simple_rte_array[rti]->inh) + build_subquery_rel_uniquekeys(root, rel); + if (rel->uniquekeys == NIL) no_uniquekey_relids = bms_add_member(no_uniquekey_relids, rti); } @@ -772,6 +794,127 @@ build_plain_rel_uniquekeys(PlannerInfo *root, RelOptInfo *rel) } } +/* + * build_subquery_rel_uniquekeys + * Build UniqueKeys for a subquery relation. + * + * A subquery can be distinct by construction: on its DISTINCT columns, on + * its GROUP BY columns, on all its output columns if it is a set operation + * without ALL, or because it returns at most one row. We make a UniqueKey + * for each of these. + * + * Those constructs consider NULLs equal to each other, so the UniqueKeys are + * null_aware. + */ +static void +build_subquery_rel_uniquekeys(PlannerInfo *root, RelOptInfo *rel) +{ + Query *subquery = root->simple_rte_array[rel->relid]->subquery; + + /* DISTINCT, though not DISTINCT ON if there are SRFs in the tlist */ + if (subquery->distinctClause && + !(subquery->hasTargetSRFs && subquery->hasDistinctOn)) + add_subquery_uniquekey(root, rel, subquery->targetList, NIL, + subquery->distinctClause); + + /* Otherwise, SRFs in the tlist can duplicate rows after any grouping */ + if (subquery->hasTargetSRFs) + return; + + if (subquery->groupClause && !subquery->groupingSets) + { + /* GROUP BY without grouping sets */ + add_subquery_uniquekey(root, rel, subquery->targetList, NIL, + subquery->groupClause); + } + else if (subquery->groupingSets) + { + /* A single empty grouping set yields at most one row */ + if (subquery->groupClause == NIL && + (subquery->groupDistinct || + list_length(expand_grouping_sets(subquery->groupingSets, + false, -1)) == 1)) + add_uniquekey(rel, NULL, true); + return; + } + else if (subquery->hasAggs || subquery->havingQual) + { + /* Aggregation without GROUP BY yields at most one row */ + add_uniquekey(rel, NULL, true); + } + + /* UNION, INTERSECT and EXCEPT, except with ALL */ + if (subquery->setOperations) + { + SetOperationStmt *topop = castNode(SetOperationStmt, + subquery->setOperations); + + if (!topop->all) + add_subquery_uniquekey(root, rel, NIL, subquery->targetList, + topop->groupClauses); + } +} + +/* + * add_subquery_uniquekey + * Subroutine for build_subquery_rel_uniquekeys: add a UniqueKey for the + * output columns that the subquery is made distinct on. + * + * The columns are those that the given SortGroupClauses refer to in + * sgc_tlist, or if out_tlist is given instead, its non-junk entries, which + * the clauses then match one by one. + * + * Each column must be in an EC that uses the opfamilies of the clause's + * equality operator and the column's collation; otherwise there is no + * UniqueKey. A column that is equal to a constant has the same value in all + * the rows of interest, so it needs no place in the UniqueKey. + */ +static void +add_subquery_uniquekey(PlannerInfo *root, RelOptInfo *rel, + List *sgc_tlist, List *out_tlist, List *clauses) +{ + Bitmapset *key_ecs = NULL; + ListCell *lc = list_head(out_tlist); + + foreach_node(SortGroupClause, sgc, clauses) + { + TargetEntry *tle; + EquivalenceClass *ec; + Var *var; + int ec_index; + + if (out_tlist != NIL) + { + /* skip resjunk columns, which have no grouping clauses */ + while (lfirst_node(TargetEntry, lc)->resjunk) + lc = lnext(out_tlist, lc); + tle = lfirst_node(TargetEntry, lc); + lc = lnext(out_tlist, lc); + } + else + { + tle = get_sortgroupclause_tle(sgc, sgc_tlist); + + /* a column that is not output cannot be matched */ + if (tle->resjunk) + return; + } + + var = makeVarFromTargetEntry(rel->relid, tle); + ec_index = find_ec_index(root, rel, (Expr *) var, + get_mergejoin_opfamilies(sgc->eqop), + exprCollation((Node *) tle->expr)); + if (ec_index < 0) + return; + + ec = list_nth_node(EquivalenceClass, root->eq_classes, ec_index); + if (!ec->ec_has_const) + key_ecs = bms_add_member(key_ecs, ec_index); + } + + add_uniquekey(rel, key_ecs, true); +} + /* * build_notnull_eclass_indexes * Find the ECs that have a member that is a column of the relation that diff --git a/src/test/regress/expected/uniquekeys.out b/src/test/regress/expected/uniquekeys.out index 83be435e0db..ce901da0f9f 100644 --- a/src/test/regress/expected/uniquekeys.out +++ b/src/test/regress/expected/uniquekeys.out @@ -199,6 +199,64 @@ select * from uk_a a left join (12 rows) reset join_collapse_limit; +-- a subquery in the join relation is asked whether it is distinct +explain (verbose, costs off) +select * from uk_a a left join + (uk_b b join (select distinct x, y from uk_c) s + on b.x = s.x and b.y = s.y) on a.x = b.id; + QUERY PLAN +----------------------------------------------------------------- + Nested Loop Left Join + Output: a.id, a.x, a.y, b.id, b.x, b.y, uk_c.x, uk_c.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, uk_c.x, uk_c.y + -> Nested Loop + Output: b.id, b.x, b.y, uk_c.x, uk_c.y + Inner Unique: true + Join Filter: ((b.x = uk_c.x) AND (b.y = uk_c.y)) + -> Index Scan using uk_b_pkey on public.uk_b b + Output: b.id, b.x, b.y + -> Materialize + Output: uk_c.x, uk_c.y + -> HashAggregate + Output: uk_c.x, uk_c.y + Group Key: uk_c.x, uk_c.y + -> Seq Scan on public.uk_c + Output: uk_c.id, uk_c.x, uk_c.y +(21 rows) + +-- which takes clauses on all of its DISTINCT columns +explain (verbose, costs off) +select * from uk_a a left join + (uk_b b join (select distinct x, y from uk_c) s + on b.x = s.x) on a.x = b.id; + QUERY PLAN +----------------------------------------------------------------- + Nested Loop Left Join + Output: a.id, a.x, a.y, b.id, b.x, b.y, uk_c.x, uk_c.y + 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, uk_c.x, uk_c.y + -> Nested Loop + Output: b.id, b.x, b.y, uk_c.x, uk_c.y + Join Filter: (b.x = uk_c.x) + -> Index Scan using uk_b_pkey on public.uk_b b + Output: b.id, b.x, b.y + -> Materialize + Output: uk_c.x, uk_c.y + -> HashAggregate + Output: uk_c.x, uk_c.y + Group Key: uk_c.x, uk_c.y + -> Seq Scan on public.uk_c + Output: uk_c.id, uk_c.x, uk_c.y +(19 rows) + -- the right-hand side of a semijoin or antijoin need not be unique explain (verbose, costs off) select * from uk_a a left join @@ -703,6 +761,80 @@ from (select * from uk_n where v > 0) n1 full join Index Cond: (v > 0) (11 rows) +-- subqueries +explain (costs off) +select distinct x, y from (select distinct x, y from uk_c) s; + QUERY PLAN +----------------------------- + HashAggregate + Group Key: uk_c.x, uk_c.y + -> Seq Scan on uk_c +(3 rows) + +explain (costs off) +select distinct b.id, s.y +from uk_b b join (select x, y from uk_c group by x, y) s on b.x = s.x; + QUERY PLAN +----------------------------------------------- + Hash Join + Hash Cond: (b.x = s.x) + -> Seq Scan on uk_b b + -> Hash + -> Subquery Scan on s + -> HashAggregate + Group Key: uk_c.x, uk_c.y + -> Seq Scan on uk_c +(8 rows) + +explain (costs off) +select distinct b.id, s.y +from uk_b b join (select id, x, y from uk_c group by id, x, y) s on b.x = s.x; + QUERY PLAN +------------------------------------------ + HashAggregate + Group Key: b.id, s.y + -> Merge Join + Merge Cond: (b.x = s.x) + -> Sort + Sort Key: b.x + -> Seq Scan on uk_b b + -> Sort + Sort Key: s.x + -> Subquery Scan on s + -> Seq Scan on uk_c +(11 rows) + +-- a lateral subquery needs the relations it refers to +explain (costs off) +select distinct a.id, s.x +from uk_a a, lateral (select distinct b.x from uk_b b where b.y = a.y) s; + QUERY PLAN +-------------------------------------------- + Nested Loop + -> Index Scan using uk_a_pkey on uk_a a + -> Unique + -> Sort + Sort Key: b.x + -> Seq Scan on uk_b b + Filter: (y = a.y) +(7 rows) + +explain (costs off) +select distinct a.x, s.x +from uk_a a, lateral (select distinct b.x from uk_b b where b.y = a.y) s; + QUERY PLAN +--------------------------------------------- + HashAggregate + Group Key: a.x, b.x + -> Nested Loop + -> Seq Scan on uk_a a + -> Unique + -> Sort + Sort Key: b.x + -> Seq Scan on uk_b b + Filter: (y = a.y) +(9 rows) + -- semijoins and antijoins explain (costs off) select distinct b.id from uk_b b diff --git a/src/test/regress/sql/uniquekeys.sql b/src/test/regress/sql/uniquekeys.sql index 6c7ea109006..62e5208e0e9 100644 --- a/src/test/regress/sql/uniquekeys.sql +++ b/src/test/regress/sql/uniquekeys.sql @@ -63,6 +63,18 @@ select * from uk_a a left join reset join_collapse_limit; +-- a subquery in the join relation is asked whether it is distinct +explain (verbose, costs off) +select * from uk_a a left join + (uk_b b join (select distinct x, y from uk_c) s + on b.x = s.x and b.y = s.y) on a.x = b.id; + +-- which takes clauses on all of its DISTINCT columns +explain (verbose, costs off) +select * from uk_a a left join + (uk_b b join (select distinct x, y from uk_c) s + on b.x = s.x) on a.x = b.id; + -- the right-hand side of a semijoin or antijoin need not be unique explain (verbose, costs off) select * from uk_a a left join @@ -200,6 +212,27 @@ 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; +-- subqueries +explain (costs off) +select distinct x, y from (select distinct x, y from uk_c) s; + +explain (costs off) +select distinct b.id, s.y +from uk_b b join (select x, y from uk_c group by x, y) s on b.x = s.x; + +explain (costs off) +select distinct b.id, s.y +from uk_b b join (select id, x, y from uk_c group by id, x, y) s on b.x = s.x; + +-- a lateral subquery needs the relations it refers to +explain (costs off) +select distinct a.id, s.x +from uk_a a, lateral (select distinct b.x from uk_b b where b.y = a.y) s; + +explain (costs off) +select distinct a.x, s.x +from uk_a a, lateral (select distinct b.x from uk_b b where b.y = a.y) s; + -- semijoins and antijoins explain (costs off) select distinct b.id from uk_b b -- 2.53.0