From 6d7540b3aa91d34f3792d6e3ba6481ab9815175a Mon Sep 17 00:00:00 2001
From: Tomas Vondra <tomas@vondra.me>
Date: Wed, 25 Nov 2026 13:47:05 +0100
Subject: [PATCH v7 01/30] Speed-up planning of starjoin-like queries

Restrict the useless reordering of joins that do not affect cardinality,
like joins to dimensions in starjoin/snowflake queries.  When a
dimension is joined to the fact through a foreign key with NOT NULL
referencing columns, and the dimension is not restricted in any other
way, each fact row matches exactly one dimension row.  All orders of
joining such dimensions to the fact produce the same row counts, yet the
standard join search considers all of them, building a joinrel for every
subset of the dimensions joined to the fact.

query_planner() now determines the starjoin clusters of the query (each
a fact with at least two dimensions), in a new function
generate_starjoin_clusters().  make_join_rel() then rejects joinrels
with the fact and two or more of its dimensions, unless the dimensions
are a prefix of the canonical order (the dimensions in relid order).
This makes the number of joinrels linear in the number of dimensions, so
planning such queries gets much cheaper.  But it may occasionally miss a
cheaper plan, as the orders may still differ in cost (e.g. due to
different widths of the dimensions).

The restriction applies only to join search subproblems including the
fact, and only to the dimensions joined individually in them, so that it
can't leave the join search without a valid join order.  GEQO is subject
to the same restriction.

Add a GUC enable_starjoin_ordering (on by default) to allow disabling
the optimization, and document it with the other planner method
configuration parameters.

Add STARJOINS.md, describing the overall design, the conditions for a
relation to be treated as a dimension, and the open questions and
issues.

Tests: join.sql checks that a simple star join gets the same plan with
the optimization enabled and disabled.  The new starjoin_* suites check
that planning succeeds when the join search is split into subproblems,
or when the last-ditch pass joins dimensions to rels without the fact,
and compare the plans and the planning memory with the optimization
enabled and disabled (see STARJOINS.md).  The _large variants are too
expensive to run by default, so they're commented out in
parallel_schedule.

Discussion: https://postgr.es/m/e64bba92-96fe-4bb3-b678-6b77169b9760@vondra.me
---
 STARJOINS.md                                  | 293 ++++++++
 doc/src/sgml/config.sgml                      |  24 +
 src/backend/optimizer/path/costsize.c         |   1 +
 src/backend/optimizer/path/joinrels.c         | 168 +++++
 src/backend/optimizer/plan/initsplan.c        | 265 +++++++
 src/backend/optimizer/plan/planmain.c         |   8 +
 src/backend/utils/misc/guc_parameters.dat     |   8 +
 src/backend/utils/misc/postgresql.conf.sample |   1 +
 src/include/nodes/pathnodes.h                 |  39 ++
 src/include/optimizer/cost.h                  |   1 +
 src/include/optimizer/planmain.h              |   1 +
 src/test/regress/expected/join.out            |  59 ++
 src/test/regress/expected/starjoin_eager.out  | 187 +++++
 .../regress/expected/starjoin_eager_large.out | 190 +++++
 src/test/regress/expected/starjoin_other.out  | 444 ++++++++++++
 src/test/regress/expected/starjoin_plan.out   | 172 +++++
 .../regress/expected/starjoin_plan_large.out  | 172 +++++
 .../regress/expected/starjoin_planning.out    | 437 ++++++++++++
 .../regress/expected/starjoin_reproducers.out | 656 ++++++++++++++++++
 src/test/regress/expected/starjoin_width.out  |  89 +++
 .../regress/expected/starjoin_width_large.out |  90 +++
 src/test/regress/expected/sysviews.out        |   3 +-
 src/test/regress/parallel_schedule            |   6 +
 src/test/regress/sql/join.sql                 |  36 +
 src/test/regress/sql/starjoin_eager.sql       |  94 +++
 src/test/regress/sql/starjoin_eager_large.sql |  97 +++
 src/test/regress/sql/starjoin_other.sql       | 422 +++++++++++
 src/test/regress/sql/starjoin_plan.sql        |  92 +++
 src/test/regress/sql/starjoin_plan_large.sql  |  92 +++
 src/test/regress/sql/starjoin_planning.sql    | 163 +++++
 src/test/regress/sql/starjoin_reproducers.sql | 326 +++++++++
 src/test/regress/sql/starjoin_width.sql       |  60 ++
 src/test/regress/sql/starjoin_width_large.sql |  61 ++
 src/tools/pgindent/typedefs.list              |   1 +
 34 files changed, 4757 insertions(+), 1 deletion(-)
 create mode 100644 STARJOINS.md
 create mode 100644 src/test/regress/expected/starjoin_eager.out
 create mode 100644 src/test/regress/expected/starjoin_eager_large.out
 create mode 100644 src/test/regress/expected/starjoin_other.out
 create mode 100644 src/test/regress/expected/starjoin_plan.out
 create mode 100644 src/test/regress/expected/starjoin_plan_large.out
 create mode 100644 src/test/regress/expected/starjoin_planning.out
 create mode 100644 src/test/regress/expected/starjoin_reproducers.out
 create mode 100644 src/test/regress/expected/starjoin_width.out
 create mode 100644 src/test/regress/expected/starjoin_width_large.out
 create mode 100644 src/test/regress/sql/starjoin_eager.sql
 create mode 100644 src/test/regress/sql/starjoin_eager_large.sql
 create mode 100644 src/test/regress/sql/starjoin_other.sql
 create mode 100644 src/test/regress/sql/starjoin_plan.sql
 create mode 100644 src/test/regress/sql/starjoin_plan_large.sql
 create mode 100644 src/test/regress/sql/starjoin_planning.sql
 create mode 100644 src/test/regress/sql/starjoin_reproducers.sql
 create mode 100644 src/test/regress/sql/starjoin_width.sql
 create mode 100644 src/test/regress/sql/starjoin_width_large.sql

diff --git a/STARJOINS.md b/STARJOINS.md
new file mode 100644
index 00000000000..a2cb2ee67e7
--- /dev/null
+++ b/STARJOINS.md
@@ -0,0 +1,293 @@
+# Star-join planning
+
+This file describes the planner optimization of star joins, controlled
+by the `enable_starjoin_ordering` GUC: the overall design, the
+conditions for a relation to be treated as a dimension, and the open
+questions and issues.
+
+## Overall design
+
+### Motivation
+
+In a star join, a fact table references several dimension tables through
+foreign keys.  When a dimension is joined to the fact through a foreign
+key with NOT NULL referencing columns, and the dimension is not
+restricted in any other way, each fact row matches exactly one dimension
+row.  All orders of joining such dimensions to the fact produce the same
+row counts, yet the standard join search considers all of them, building
+a joinrel for every subset of the dimensions joined to the fact.  With d
+dimensions, that's 2^d subsets, each combined with every set of the
+other rels joined to the fact.  Restricting the join search to a
+canonical order of the dimensions makes the number of these joinrels
+linear in the number of dimensions, so planning such queries gets much
+cheaper.
+
+The restriction never changes the query results, only the join orders
+the search considers.  But the orders may still differ in cost (e.g. due
+to different widths of the dimensions), so the planner may occasionally
+miss a cheaper plan.  A relation treated as a dimension although its
+join does not preserve the fact rows can only make the planner miss a
+cheaper plan too, e.g. by postponing a selective join.
+
+### Parts
+
+The optimization consists of these parts:
+
+- The `enable_starjoin_ordering` GUC (on by default), documented with
+  the other planner method configuration parameters.  With the GUC
+  disabled, no clusters are built, so the join search is not restricted.
+- `generate_starjoin_clusters` determines the starjoin clusters of the
+  query.  `query_planner` calls it after matching the foreign keys to
+  the join clauses, once the lateral, placeholder and special join
+  information is available.  It keeps the clusters in the
+  `starjoin_clusters` list of `PlannerInfo`, as `StarJoinClusterInfo`
+  nodes.  Like other planner-only nodes, `StarJoinClusterInfo` needs no
+  copy, equal, read or query jumble support.
+- `starjoin_order_invalid`, called by `make_join_rel`, rejects joins
+  violating the canonical order, just like various other join
+  restrictions.
+
+The clusters are determined in `src/backend/optimizer/plan/initsplan.c`,
+and the join order is restricted in
+`src/backend/optimizer/path/joinrels.c`.
+
+### Starjoin clusters
+
+A starjoin cluster is a fact (a base relation) with at least two
+dimensions.  A dimension is a relation referenced by a foreign key of
+the fact, fully matched by the join clauses, and satisfying the
+conditions described below.  `generate_starjoin_clusters` groups the
+foreign keys matched to the join clauses by the referencing and the
+referenced relation, checks the conditions for each relation referenced
+by a fact, and builds a cluster for each fact with at least two
+qualifying dimensions.  A relation failing the conditions is simply not
+a dimension of the cluster, and gets joined like any other rel.
+
+The clusters are disjoint.  A relation referenced by two facts has join
+clauses to both, so it's a dimension of neither, and a fact has join
+clauses to its dimensions, so it's not a dimension of another cluster.
+In a snowflake schema, a dimension with its own dimensions is not a
+member of the cluster (it has join clauses to them), but it may be the
+fact of another cluster.
+
+### The canonical order
+
+The canonical order of a cluster joins the dimensions in relid order,
+which is usually the order in which they appear in the query.
+
+`starjoin_order_invalid` restricts the joins where both inputs contain
+dimensions of a cluster, and the result contains the fact.  The
+dimensions in such a joinrel have to be a prefix of the canonical order,
+so there must be no dimension after the first missing one.  It's enough
+to check these joins, as otherwise all the dimensions come from one
+input, which was checked when it was built.  So joinrels with the fact
+and a single dimension are not restricted, and both "(f JOIN d1) JOIN
+d2" and "(f JOIN d2) JOIN d1" are considered.  For each set of the other
+rels, the search builds a joinrel with the fact and each of the d
+dimensions, and then the longer prefixes of the canonical order, so
+about 2d joinrels with the fact instead of 2^d.
+
+### Joinrels without the fact
+
+Joins without the fact are not restricted, even in subproblems including
+the fact.  The dimensions have join clauses only to the fact (and no
+join order restrictions), so `join_search_one_level` joins them to rels
+without the fact only by cartesian products, e.g. in the last-ditch
+pass, when no other join is possible at that level.  Such joins with
+dimensions on both sides are rare, but possible: if the other rels have
+join clauses usable only at a later level, two such joinrels (each with
+a different dimension) may get joined.  The canonical order is not
+enforced for them, for the same reason as in subproblems without the
+fact (see below).
+
+### Join search subproblems
+
+The clusters are determined for the whole query, but the join search may
+be split into multiple subproblems (`join_collapse_limit`,
+`from_collapse_limit`, FULL JOIN), each solved separately.  The
+restriction applies only to subproblems including the fact, and only to
+dimensions that are initial rels of the subproblem (base relations
+joined individually).  Dimensions joined into a joinrel by an earlier
+subproblem (possibly together with the fact) are treated like any other
+rel.  Otherwise the restriction might leave no valid join order, and
+planning would fail with "failed to build any N-way joins".
+
+The canonical order must not be enforced without the fact.  It relies on
+joins of dimensions to the fact not changing the cardinality of the
+fact.  Without the fact, the dimensions can only be joined by cartesian
+products (they have join clauses only to the fact), which do change the
+cardinality, so the order matters, and enforcing it might eliminate the
+cheapest plan.  The product of the dimensions is then joined to the fact
+in an upper subproblem, where the dimensions are not initial rels, and
+so are not checked.
+
+`starjoin_order_invalid` walks the initial rels of the current
+subproblem on each call, to find the base rels of the subproblem, and
+whether it contains the fact of each cluster.
+
+### Why the join search cannot fail
+
+The dimensions are interchangeable, as they have join clauses only to
+the fact, and no join order restrictions.  So for each pruned joinrel
+with the fact, the search builds the joinrel with the dimensions
+replaced by the first ones in the canonical order.  The pruning
+therefore can't make the join search fail.
+
+### GEQO
+
+GEQO is subject to the same restriction, as it builds the joinrels using
+`make_join_rel` too.  It joins a dimension only to the clump with the
+fact (the only desirable join), and a dimension that can't be joined yet
+remains a separate clump.  GEQO tries to merge it again whenever the
+clump with the fact grows, and at the end it force-joins the remaining
+clumps, so it still finds a plan.
+
+## Conditions for a dimension
+
+A relation is a dimension of a fact if it's referenced by a foreign key
+of the fact, the join clauses between them fully match the foreign key,
+and it satisfies the conditions below.  The conditions are numbered as
+in the comment of `generate_starjoin_clusters`.  They make sure each
+fact row matches exactly one row of the dimension, and that the
+dimension can be joined to the fact at any point of the join search.
+The fact has to be a base relation too.
+
+1. The dimension is a plain base relation (`RELOPT_BASEREL`).
+
+2. All join columns on the fact are NOT NULL.
+
+   A NULL never matches, so the join would remove a fact row with a NULL
+   reference.  The check uses the NOT NULL constraints of the columns
+   (`notnullattnums`).
+
+3. The dimension has no local restriction quals (`baserestrictinfo`).
+
+   A restriction removes some dimension rows, so some fact rows might
+   lose their match.
+
+4. The dimension has no relevant join clauses to any rel other than the
+   fact (checked via `have_relevant_joinclause`, which also covers
+   equivalence class joins).
+
+   So the dimension can be joined only to the fact (or to joinrels
+   including it), which makes the dimensions interchangeable.
+
+5. The dimension does not participate in any `SpecialJoinInfo`.
+
+6. The dimension has no lateral references in or out.
+
+7. The dimension is not constrained by any `PlaceHolderInfo`.
+
+   Conditions 5 to 7 rule out join order restrictions on the dimension.
+
+### Foreign key requirements
+
+If the fact has several foreign keys referencing the dimension, the
+conditions are checked for the first one in `fkey_list`.
+
+### Conditions inherited from foreign key matching
+
+The clusters are built from the foreign keys the planner matches to the
+join clauses for selectivity estimation (`fkey_list`), so they inherit
+its conditions:
+
+- Foreign keys that are not enforced are ignored, while NOT VALID ones
+  are used (see the open issues).
+- The foreign keys of an inheritance parent are ignored, so it can't be
+  a fact.
+- The referenced range table entry has to be a plain relation without
+  inheritance, so an inheritance parent can't be a dimension.
+- Self-referential foreign keys are ignored.
+- Only foreign keys between two base relations, fully matched by the
+  join clauses, are kept.
+
+## Open questions and issues
+
+None of these can make a query return wrong results.  They affect only
+the plans, the planning cost, or the regression tests.
+
+- The restriction could be made even stricter, if needed, e.g. to
+  effectively join all the dimensions at once, with no other joins in
+  between.
+- A dimension can't be joined by an outer join (condition 5), although a
+  LEFT JOIN to a dimension preserves the fact rows too, as long as the
+  dimension has a unique constraint on the join columns.  The condition
+  could be relaxed to allow such left joins.
+- The canonical order is the relid order, as the cluster keeps its
+  dimensions in a bitmap of relids.  Allowing snowflake joins (a
+  dimension with its own dimensions as a member of the cluster) would
+  need an explicit, ordered list of the dimensions.
+- NOT VALID foreign keys are trusted, as in selectivity estimation,
+  although some referencing rows need not have a match.  That can affect
+  only the plan quality.
+- Even if all the joins preserve the cardinality, the join orders don't
+  have the same cost.  With a small `work_mem`, the hash join to a large
+  dimension needs multiple batches, and the cost of batching depends on
+  the width of the outer rows, so it's much cheaper to join the large
+  dimension before the wide ones.  If the canonical order joins it last,
+  the planner misses the cheaper plan.  This is shown by
+  starjoin_width_large, and by the width_cost_higher check in
+  starjoin_other.  There's no fix, as this comes with considering a
+  single order.
+- With GROUP BY on a column of a dimension, eager aggregation can place
+  a partial aggregate on the join of the fact and the other dimensions,
+  and then join the grouping dimension.  With the canonical order, that
+  joinrel is built only if the grouping dimension is the last one, so
+  the plan depends on the order of the dimensions in the FROM clause
+  (see starjoin_eager, and the eager_first_partial_agg_on check in
+  starjoin_other).  A possible direction, not tried yet, is an explicit
+  canonical order putting the dimensions with grouping columns last.
+- Joins where one side has no cluster dimensions are not checked, so the
+  join search still builds the joinrels of the fact with each single
+  dimension, and e.g. "(f JOIN d2) JOIN d1" passes the check too.  For a
+  star with 10 dimensions, the search builds 19 joinrels instead of the
+  10 in the canonical order, and uses more memory than planning the
+  canonical order (the flat_search_canonical check in starjoin_other).
+- A dimension in any relid set of a `SpecialJoinInfo` is rejected,
+  including the syntactic ones (`syn_lefthand` and `syn_righthand`).  So
+  a LEFT JOIN or a semijoin (EXISTS) placed after the star joins
+  disables the optimization, even if it references only the fact, while
+  writing the LEFT JOIN first works (the left_join_last_pruned and
+  exists_pruned checks in starjoin_other).
+- The conditions check the join clauses of a dimension to other rels,
+  but not additional join clauses to the fact (not matching the foreign
+  key).  Such a clause makes the join selective, so the dimension should
+  be joined first, but the canonical order may join it last (the
+  extra_clause_cost_higher check in starjoin_other, and starjoin_plan).
+- The search might forbid additional joins, e.g. joinrels containing a
+  dimension of a cluster but not its fact.
+
+## Regression tests
+
+- join.sql checks that a simple star join gets the same plan with the
+  GUC enabled and disabled.
+- starjoin_planning checks that planning succeeds when the join search
+  is split into subproblems.
+- starjoin_reproducers checks queries where the clusters (determined for
+  the whole query) and the join search subproblems don't align, so the
+  canonical order can't be followed in some subproblem, and a query
+  where the last-ditch pass joins dimensions to rels without the fact.
+  For each query, it shows the plan with the GUC enabled, and checks
+  that the query returns the same result with the GUC enabled and
+  disabled.
+- starjoin_eager, starjoin_plan and starjoin_width compare the plans
+  with the GUC enabled and disabled, for star joins combined with eager
+  aggregation, with extra join clauses between the fact and a dimension,
+  and with dimensions of very different widths.  They normalize the
+  EXPLAIN ANALYZE output, to ignore platform-dependent memory usage and
+  hash table sizing, while retaining the actual row counts and the
+  distinction between single-batch and multi-batch hash joins.  With
+  `work_mem` set to 4MB in starjoin_width, its plans are the same with
+  the GUC enabled and disabled.
+- The _large variants of these three suites use larger tables, and
+  starjoin_eager_large and starjoin_width_large set `work_mem` to 400kB,
+  so that their hash joins need multiple batches.  They're too expensive
+  to run by default, so they're commented out in parallel_schedule.
+- starjoin_other checks various other cases, mostly by comparing the
+  plan costs or the planning memory (reported by EXPLAIN (MEMORY)) with
+  the GUC enabled and disabled.  The cases include extra join clauses
+  between the fact and a dimension, OR clauses, dimensions of very
+  different widths, outer joins and semijoins, stars split into
+  subproblems, GEQO, and eager aggregation.  Each check is a single
+  boolean, so that the output does not depend on platform-specific costs
+  or memory usage, and some checks show the known limitations.
diff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgml
index 7018ca1e3ea..8f04e2cba4a 100644
--- a/doc/src/sgml/config.sgml
+++ b/doc/src/sgml/config.sgml
@@ -6312,6 +6312,30 @@ ANY <replaceable class="parameter">num_sync</replaceable> ( <replaceable class="
       </listitem>
      </varlistentry>
 
+     <varlistentry id="guc-enable-starjoin-ordering" xreflabel="enable_starjoin_ordering">
+      <term><varname>enable_starjoin_ordering</varname> (<type>boolean</type>)
+      <indexterm>
+       <primary><varname>enable_starjoin_ordering</varname> configuration parameter</primary>
+      </indexterm>
+      </term>
+      <listitem>
+       <para>
+        Enables or disables the query planner's optimization of star joins,
+        where a <quote>fact</quote> table is joined to multiple
+        <quote>dimension</quote> tables using foreign keys.  When a dimension
+        table is joined only to the fact table, using a join condition
+        matching a foreign key with <literal>NOT NULL</literal> referencing
+        columns, joining it does not change the number of rows.  All orders
+        of joining such dimension tables to the fact table thus produce the
+        same number of rows, and the planner considers only one of them.
+        This can significantly reduce planning time for queries joining many
+        dimension tables, but may occasionally miss a cheaper join order.
+        Only inner joins of plain tables, with no other conditions on the
+        dimension tables, are optimized.  The default is <literal>on</literal>.
+       </para>
+      </listitem>
+     </varlistentry>
+
      <varlistentry id="guc-enable-tidscan" xreflabel="enable_tidscan">
       <term><varname>enable_tidscan</varname> (<type>boolean</type>)
       <indexterm>
diff --git a/src/backend/optimizer/path/costsize.c b/src/backend/optimizer/path/costsize.c
index 7bbddb8bee4..1dfbc6c620c 100644
--- a/src/backend/optimizer/path/costsize.c
+++ b/src/backend/optimizer/path/costsize.c
@@ -165,6 +165,7 @@ bool		enable_parallel_hash = true;
 bool		enable_partition_pruning = true;
 bool		enable_presorted_aggregate = true;
 bool		enable_async_append = true;
+bool		enable_starjoin_ordering = true;
 
 typedef struct
 {
diff --git a/src/backend/optimizer/path/joinrels.c b/src/backend/optimizer/path/joinrels.c
index cf95021db75..b72413c43a9 100644
--- a/src/backend/optimizer/path/joinrels.c
+++ b/src/backend/optimizer/path/joinrels.c
@@ -32,6 +32,9 @@ static void make_rels_by_clause_joins(PlannerInfo *root,
 static void make_rels_by_clauseless_joins(PlannerInfo *root,
 										  RelOptInfo *old_rel,
 										  List *other_rels);
+static bool starjoin_order_invalid(PlannerInfo *root,
+								   RelOptInfo *rel1,
+								   RelOptInfo *rel2);
 static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel);
 static bool has_legal_joinclause(PlannerInfo *root, RelOptInfo *rel);
 static bool restriction_is_constant_false(List *restrictlist,
@@ -756,6 +759,15 @@ make_join_rel(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
 	/* We should never try to join two overlapping sets of rels. */
 	Assert(!bms_overlap(rel1->relids, rel2->relids));
 
+	/*
+	 * If this join would be a redundant ordering of a previously detected
+	 * starjoin cluster, skip it. All cluster orderings produce the same
+	 * number of rows (the costs may differ, see generate_starjoin_clusters),
+	 * so we consider only the canonical one, chosen when building clusters.
+	 */
+	if (starjoin_order_invalid(root, rel1, rel2))
+		return NULL;
+
 	/* Construct Relids set that identifies the joinrel (without OJ as yet). */
 	joinrelids = bms_union(rel1->relids, rel2->relids);
 
@@ -2159,3 +2171,159 @@ get_matching_part_pairs(PlannerInfo *root, RelOptInfo *joinrel,
 		*parts2 = lappend(*parts2, child_rel2);
 	}
 }
+
+/*
+ * starjoin_order_invalid
+ *		Return true if the proposed join (rel1, rel2) would build a
+ *		non-canonical ordering of a starjoin cluster.
+ *
+ * For every star cluster in root->starjoin_clusters, we enforce the canonical
+ * decomposition of any joinrel containing the fact and at least one cluster
+ * dimension - the dimensions must form a prefix of the order determined when
+ * collecting the starjoin clusters.
+ *
+ * Clusters are computed for the whole query, but the join search may be split
+ * into multiple subproblems (join_collapse_limit, from_collapse_limit, FULL
+ * JOIN), and each subproblem is solved separately. Within a subproblem, only
+ * dimensions that are initial rels of that subproblem (i.e. base relations
+ * joined individually) can be added in the canonical order.  Dimensions
+ * already joined into a joinrel by an earlier subproblem (possibly together
+ * with the fact) can't, so we ignore them here and treat their joinrel just
+ * like any other relation.  Otherwise there might be no valid join order at
+ * all.  Clusters with the fact outside the current subproblem are ignored.
+ *
+ * This rule preserves exactly one decomposition per joinrel relid set, so
+ * each canonical joinrel is still built; redundant orderings are pruned.
+ *
+ * GEQO is subject to the same check.  It joins a dimension only to the clump
+ * with the fact (the only desirable join), and a dimension that can't be
+ * joined yet remains a separate clump.  But whenever the clump with the fact
+ * grows, GEQO tries to merge it with the other clumps again, and at the end
+ * it force-joins the remaining clumps (joins without the fact are not
+ * restricted), so it still finds a plan.
+ *
+ * We might forbid additional joins, for example we might forbid joinrels
+ * containing a cluster dimension without the fact.
+ */
+static bool
+starjoin_order_invalid(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
+{
+	ListCell   *lc;
+	Relids		join_relids;
+	Relids		all_relids = NULL;	/* all relids in this subproblem */
+	Relids		baserel_relids = NULL;	/* baserels in this subproblem */
+	bool		violates = false;
+
+	/* no starjoins found (maybe because the option is disabled) */
+	if (root->starjoin_clusters == NIL)
+		return false;
+
+	/* The initial rels of the current subproblem. */
+	foreach(lc, root->initial_rels)
+	{
+		RelOptInfo *rel = (RelOptInfo *) lfirst(lc);
+
+		all_relids = bms_add_members(all_relids, rel->relids);
+		if (rel->reloptkind == RELOPT_BASEREL)
+			baserel_relids = bms_add_members(baserel_relids, rel->relids);
+	}
+
+	/* relids of the result */
+	join_relids = bms_union(rel1->relids, rel2->relids);
+
+	/* does this contradict any of the clusters we know about */
+	foreach(lc, root->starjoin_clusters)
+	{
+		StarJoinClusterInfo *c = (StarJoinClusterInfo *) lfirst(lc);
+		Relids		cluster_dims;
+		bool		gap = false;
+		int			idx;
+
+		/*
+		 * The fact is not part of this subproblem, nothing to enforce.
+		 *
+		 * We must not enforce the canonical order without the fact.  The
+		 * order relies on joins of dimensions to the fact not changing the
+		 * cardinality of the fact.  Without the fact, the dimensions can only
+		 * be joined by cartesian products (they have join clauses only to the
+		 * fact), which do change the cardinality, so the order matters and
+		 * enforcing it might eliminate the cheapest plan.  The joinrel is
+		 * joined to the fact in an upper subproblem, where the dimensions are
+		 * not initial rels, and so are not checked.
+		 *
+		 * Snowflake joins are not an exception: a dimension with its own
+		 * dimensions is not a member of this cluster, but it may be the fact
+		 * of another cluster, enforced in subproblems including it.
+		 */
+		if (!bms_is_member(c->fact_relid, all_relids))
+			continue;
+
+		/* dimensions joined individually in this subproblem */
+		cluster_dims = bms_intersect(c->dim_relids, baserel_relids);
+
+		/*
+		 * If all dimensions are on one side of the join, we've already
+		 * checked the canonical order earlier, when building it. No need to
+		 * redo the check again.
+		 */
+		if (!bms_overlap(rel1->relids, cluster_dims) ||
+			!bms_overlap(rel2->relids, cluster_dims))
+		{
+			bms_free(cluster_dims);
+			continue;
+		}
+
+		/*
+		 * Joins without the fact are not restricted either, for the same
+		 * reason as above.  Such joins with dimensions on both sides are
+		 * rare, but possible.  The dimensions have join clauses only to the
+		 * fact (and no join order restrictions), so join_search_one_level
+		 * joins them to rels without the fact only by cartesian products,
+		 * e.g. in the last-ditch pass, when no other join is possible at that
+		 * level.  But the other rel may have join clauses usable only at a
+		 * later level, and so two such joinrels (each with a different
+		 * dimension) may get joined.
+		 */
+		if (!bms_is_member(c->fact_relid, join_relids))
+		{
+			bms_free(cluster_dims);
+			continue;
+		}
+
+		/*
+		 * The dimensions in the join have to be a prefix of the cluster
+		 * dimensions (in relid order), i.e. there must be no dimension after
+		 * the first gap.
+		 *
+		 * XXX Using the relid order is fine for now, but if we choose to
+		 * allow snowflake joins, we'll need an explicit (ordered) list.
+		 */
+		idx = -1;
+		while ((idx = bms_next_member(cluster_dims, idx)) >= 0)
+		{
+			/*
+			 * A missing dimension is fine on its own, as the join may not
+			 * include all the dimensions yet.  It's a violation only if the
+			 * join includes a dimension after it.
+			 */
+			if (!bms_is_member(idx, join_relids))
+				gap = true;
+			else if (gap)
+			{
+				violates = true;
+				break;
+			}
+		}
+
+		bms_free(cluster_dims);
+
+		if (violates)
+			break;
+	}
+
+	bms_free(join_relids);
+	bms_free(all_relids);
+	bms_free(baserel_relids);
+
+	return violates;
+}
diff --git a/src/backend/optimizer/plan/initsplan.c b/src/backend/optimizer/plan/initsplan.c
index d2dd1d68868..07776c13e02 100644
--- a/src/backend/optimizer/plan/initsplan.c
+++ b/src/backend/optimizer/plan/initsplan.c
@@ -4111,3 +4111,268 @@ check_memoizable(RestrictInfo *restrictinfo)
 			restrictinfo->right_hasheqoperator = typentry->eq_opr;
 	}
 }
+
+/*
+ * generate_starjoin_clusters
+ *		Detect star-shaped sub-joins and determine canonical join order.
+ *
+ * A starjoin cluster is a fact relation joined to two or more dimensions
+ * via an equality condition matching a foreign key, satisfying these
+ * conditions:
+ *
+ *	1. The dimension is a plain base relation (RELOPT_BASEREL).
+ *
+ *	2. All join columns on the fact are NOT NULL.
+ *
+ *	3. The dimension has no local restriction quals (baserestrictinfo).
+ *
+ *	4. The dimension has no relevant join clauses to any rel other than
+ *	   the fact (checked via have_relevant_joinclause, which also covers
+ *	   equivalence-class joins).
+ *
+ *	5. The dimension does not participate in any SpecialJoinInfo.
+ *
+ *	6. The dimension has no lateral references in or out.
+ *
+ *	7. The dimension is not constrained by any PlaceHolderInfo.
+ *
+ * Under these conditions, the join is strictly cardinality-preserving with
+ * respect to the fact table, and all join orderings for a cluster produce
+ * the same row counts.  The costs are not necessarily the same (e.g. the
+ * width of intermediate results affects hash joins that need multiple
+ * batches), so considering only a single canonical ordering may miss the
+ * cheapest plan, in exchange for considering far fewer join orders.
+ *
+ * XXX We don't check that the foreign key is the only join condition between
+ * the fact and the dimension.  Additional join clauses (e.g. a second foreign
+ * key) may eliminate fact rows, in which case the order does matter.
+ *
+ * Dimensions that fail the preconditions are simply not added to any
+ * cluster; the planner then handles them in the ordinary way.  A fact
+ * with fewer than two qualifying dimensions produces no cluster (there
+ * is nothing to deduplicate).
+ *
+ * Must be called after match_foreign_keys_to_quals(), and after lateral,
+ * PHV and SpecialJoinInfo information have been finalized.
+ *
+ * Clusters are global, for the whole query. It ignores how the whole join
+ * problem got split into smaller problems (join_collapse_limit,
+ * from_collapse_limit, FULL JOIN). We need to be careful about that when
+ * evaluating the join orders, see starjoin_order_invalid.
+ */
+void
+generate_starjoin_clusters(PlannerInfo *root)
+{
+	int			nrels;
+	List	  **fact_dims;
+	int			f;
+	ListCell   *lc;
+
+	/* do nothing if optimization not enabled */
+	if (!enable_starjoin_ordering)
+		return;
+
+	/* also, do nothing if there are no foreign key joins */
+	if (root->fkey_list == NIL)
+		return;
+
+	nrels = root->simple_rel_array_size;
+	fact_dims = (List **) palloc0(nrels * sizeof(List *));
+
+	/*
+	 * Group fully-matched FKs by referencing (fact) relid, collecting
+	 * candidate dimension relids. match_foreign_keys_to_quals() has already
+	 * filtered fkey_list to fully-matched FKs.
+	 */
+	foreach(lc, root->fkey_list)
+	{
+		ForeignKeyOptInfo *fkinfo = (ForeignKeyOptInfo *) lfirst(lc);
+		Index		fact_rti = fkinfo->con_relid;
+		Index		dim_rti = fkinfo->ref_relid;
+
+		/*
+		 * Expect valid RTI on both sides (otherwise we should not have kept
+		 * this foreign key). Similarly, we shouldn't get a FK with the same
+		 * RTI on both ends.
+		 */
+		Assert(fact_rti < root->simple_rel_array_size);
+		Assert(dim_rti < root->simple_rel_array_size);
+		Assert(fact_rti != dim_rti);
+
+		/*
+		 * With duplicate foreign keys we might have already included this
+		 * candidate dimension.
+		 */
+		if (list_member_int(fact_dims[fact_rti], dim_rti))
+			continue;
+
+		/* found a candidate dimension, stash it to the list */
+		fact_dims[fact_rti] = lappend_int(fact_dims[fact_rti], dim_rti);
+	}
+
+	/*
+	 * For each candidate fact, validate which dimensions meet the other
+	 * requirements, and build a StarJoinClusterInfo if at least two
+	 * dimensions qualify.
+	 */
+	for (f = 1; f < nrels; f++)
+	{
+		RelOptInfo *fact_rel;
+		Relids		dim_relids = NULL;
+		int			ndims = 0;
+		ListCell   *lc2;
+		StarJoinClusterInfo *cluster;
+
+		/*
+		 * Can't be a fact if there are no potential dimensions (we need at
+		 * least two for a starjoin optimization to matter).
+		 */
+		if (list_length(fact_dims[f]) < 2)
+			continue;
+
+		/* has to be a baserel (how else could it be, if it has a FK?) */
+		fact_rel = root->simple_rel_array[f];
+		if (fact_rel == NULL || fact_rel->reloptkind != RELOPT_BASEREL)
+			continue;
+
+		/* count dimensions matching the requirements */
+		foreach(lc2, fact_dims[f])
+		{
+			Index		d = (Index) lfirst_int(lc2);
+			RelOptInfo *dim_rel = root->simple_rel_array[d];
+			ForeignKeyOptInfo *fkinfo = NULL;
+			ListCell   *lc3;
+			bool		ok = true;
+			int			colno;
+			int			r;
+
+			/* has to be a baserel (it's referenced by a FK, so?) */
+			if (dim_rel == NULL || dim_rel->reloptkind != RELOPT_BASEREL)
+				continue;
+
+			/* No local restriction quals on the dimension. */
+			if (dim_rel->baserestrictinfo != NIL)
+				continue;
+
+			/* No lateral references in or out. */
+			if (!bms_is_empty(dim_rel->lateral_relids))
+				continue;
+			if (!bms_is_empty(dim_rel->lateral_referencers))
+				continue;
+
+			/* Find the matching FK so we can check NOT NULL on conkey cols */
+			foreach(lc3, root->fkey_list)
+			{
+				ForeignKeyOptInfo *fki = (ForeignKeyOptInfo *) lfirst(lc3);
+
+				if ((fki->con_relid == f) && (fki->ref_relid == d))
+				{
+					fkinfo = fki;
+					break;
+				}
+			}
+
+			/* we should have found a FK, that's how we got the array */
+			Assert(fkinfo != NULL);
+
+			/*
+			 * Make sure all columns on the fact side are NOT NULL. We know
+			 * the FK is fully matched by the join, so use that.
+			 */
+			for (colno = 0; colno < fkinfo->nkeys; colno++)
+			{
+				if (!bms_is_member(fkinfo->conkey[colno],
+								   fact_rel->notnullattnums))
+				{
+					ok = false;
+					break;
+				}
+			}
+			if (!ok)
+				continue;
+
+			/*
+			 * Should not be involved in any SpecialJoinInfo (for now the
+			 * starjoin is done only for inner joins).
+			 *
+			 * XXX We could relax this, and allow left joins, as long as the
+			 * target has a unique constraint.
+			 */
+			foreach(lc3, root->join_info_list)
+			{
+				SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) lfirst(lc3);
+
+				if (bms_is_member(d, sjinfo->min_lefthand) ||
+					bms_is_member(d, sjinfo->min_righthand) ||
+					bms_is_member(d, sjinfo->syn_lefthand) ||
+					bms_is_member(d, sjinfo->syn_righthand))
+				{
+					ok = false;
+					break;
+				}
+			}
+			if (!ok)
+				continue;
+
+			/* Not constrained by any PlaceHolderInfo. */
+			foreach(lc3, root->placeholder_list)
+			{
+				PlaceHolderInfo *phi = (PlaceHolderInfo *) lfirst(lc3);
+
+				if (bms_is_member((int) d, phi->ph_eval_at) ||
+					bms_is_member((int) d, phi->ph_lateral) ||
+					bms_is_member((int) d, phi->ph_needed))
+				{
+					ok = false;
+					break;
+				}
+			}
+			if (!ok)
+				continue;
+
+			/*
+			 * The dimension must have no relevant join clause to any rel
+			 * other than the fact.  have_relevant_joinclause() also covers
+			 * equivalence-class joins.
+			 */
+			for (r = 1; r < nrels; r++)
+			{
+				RelOptInfo *other_rel;
+
+				if (r == (int) d || r == f)
+					continue;
+				other_rel = root->simple_rel_array[r];
+				if (other_rel == NULL ||
+					other_rel->reloptkind != RELOPT_BASEREL)
+					continue;
+				if (have_relevant_joinclause(root, dim_rel, other_rel))
+				{
+					ok = false;
+					break;
+				}
+			}
+			if (!ok)
+				continue;
+
+			/* Qualifies as a dimension. */
+			dim_relids = bms_add_member(dim_relids, (int) d);
+			ndims++;
+		}
+
+		/* we need at least 2 dimensions for this optimization to matter */
+		if (ndims < 2)
+		{
+			bms_free(dim_relids);
+			continue;
+		}
+
+		/* remember this cluster */
+		cluster = makeNode(StarJoinClusterInfo);
+		cluster->fact_relid = (Index) f;
+		cluster->dim_relids = dim_relids;
+
+		root->starjoin_clusters = lappend(root->starjoin_clusters, cluster);
+	}
+
+	pfree(fact_dims);
+}
diff --git a/src/backend/optimizer/plan/planmain.c b/src/backend/optimizer/plan/planmain.c
index 9045c490486..600a9594ef6 100644
--- a/src/backend/optimizer/plan/planmain.c
+++ b/src/backend/optimizer/plan/planmain.c
@@ -110,6 +110,7 @@ restart:
 	root->group_expr_list = NIL;
 	root->tlist_vars = NIL;
 	root->fkey_list = NIL;
+	root->starjoin_clusters = NIL;
 	root->initial_rels = NIL;
 	root->hasPseudoConstantQuals = false;
 
@@ -332,6 +333,13 @@ restart:
 	 */
 	extract_restriction_or_clauses(root);
 
+	/*
+	 * Detect star-shaped sub-joins so that join_search can skip enumerating
+	 * equivalent join orderings.  Must be done after foreign keys are matched
+	 * to quals and after lateral, PHV and SpecialJoinInfo info is available.
+	 */
+	generate_starjoin_clusters(root);
+
 	/*
 	 * Check if eager aggregation is applicable, and if so, set up
 	 * root->agg_clause_list and root->group_expr_list.
diff --git a/src/backend/utils/misc/guc_parameters.dat b/src/backend/utils/misc/guc_parameters.dat
index 75d832eb570..566914f1344 100644
--- a/src/backend/utils/misc/guc_parameters.dat
+++ b/src/backend/utils/misc/guc_parameters.dat
@@ -1041,6 +1041,14 @@
   boot_val => 'true',
 },
 
+{ name => 'enable_starjoin_ordering', type => 'bool', context => 'PGC_USERSET', group => 'QUERY_TUNING_METHOD',
+  short_desc => 'Enables collapsing of redundant join orderings in star-shaped queries.',
+  long_desc => 'When enabled, the planner detects star joins (a fact table joined to multiple dimension tables via foreign keys referencing unique keys, with NOT NULL FK columns and no dimension-side restrictions) and considers only one order of joining the dimensions, as all the orders produce the same number of rows. This reduces planning time, but may occasionally miss a cheaper join order.',
+  flags => 'GUC_EXPLAIN',
+  variable => 'enable_starjoin_ordering',
+  boot_val => 'true',
+},
+
 { name => 'enable_tidscan', type => 'bool', context => 'PGC_USERSET', group => 'QUERY_TUNING_METHOD',
   short_desc => 'Enables the planner\'s use of TID scan plans.',
   flags => 'GUC_EXPLAIN',
diff --git a/src/backend/utils/misc/postgresql.conf.sample b/src/backend/utils/misc/postgresql.conf.sample
index 01f98de8a9f..26a4aeaa17a 100644
--- a/src/backend/utils/misc/postgresql.conf.sample
+++ b/src/backend/utils/misc/postgresql.conf.sample
@@ -452,6 +452,7 @@
 #enable_distinct_reordering = on
 #enable_self_join_elimination = on
 #enable_eager_aggregate = on
+#enable_starjoin_ordering = on
 
 # - Planner Cost Constants -
 
diff --git a/src/include/nodes/pathnodes.h b/src/include/nodes/pathnodes.h
index 2ba1dbfb67f..99aeb253c54 100644
--- a/src/include/nodes/pathnodes.h
+++ b/src/include/nodes/pathnodes.h
@@ -515,6 +515,14 @@ struct PlannerInfo
 	/* list of ForeignKeyOptInfos */
 	List	   *fkey_list;
 
+	/*
+	 * List of StarJoinClusterInfo entries describing detected star-shaped
+	 * sub-joins (a fact table joined to multiple FK-unique dimensions). Used
+	 * by join_search to skip enumeration of equivalent join orderings.
+	 * Populated by generate_starjoin_clusters().
+	 */
+	List	   *starjoin_clusters;
+
 	/* desired pathkeys for query_planner() */
 	List	   *query_pathkeys;
 
@@ -1503,6 +1511,37 @@ typedef struct ForeignKeyOptInfo
 	List	   *rinfos[INDEX_MAX_KEYS];
 } ForeignKeyOptInfo;
 
+/*
+ * StarJoinClusterInfo
+ *		Description of a star-shaped sub-join detected by the planner.
+ *
+ * A "star cluster" consists of a single "fact" base relation joined to a
+ * set of "dimension" base relations.  For the cluster to be recognized,
+ * each dimension must be joined to the fact via an equality condition that
+ * matches a foreign key on the fact referencing the dimension. The columns
+ * on the fact must all be NOT NULL, and the dimension must have no other
+ * join clauses, no local restriction quals, no participation in special
+ * joins or lateral references, etc. (see generate_starjoin_clusters for
+ * the full list of preconditions).
+ *
+ * When all of these conditions hold, every join ordering that has the fact
+ * as the driver produces the same row counts.  The costs may still differ
+ * (e.g. due to the width of intermediate results), but join_search considers
+ * just one canonical ordering of the cluster, to reduce the number of join
+ * orders to consider.
+ *
+ * The bitmap of dimensions determines the canonical join order.
+ */
+typedef struct StarJoinClusterInfo
+{
+	pg_node_attr(no_copy_equal, no_read, no_query_jumble)
+
+	NodeTag		type;
+	Index		fact_relid;		/* index of the fact relation */
+	Relids		dim_relids;		/* indexes of the dimension relations */
+} StarJoinClusterInfo;
+
+
 /*
  * StatisticExtInfo
  *		Information about extended statistics for planning/optimization
diff --git a/src/include/optimizer/cost.h b/src/include/optimizer/cost.h
index 14255c900fc..28b91195a4d 100644
--- a/src/include/optimizer/cost.h
+++ b/src/include/optimizer/cost.h
@@ -71,6 +71,7 @@ extern PGDLLIMPORT bool enable_parallel_hash;
 extern PGDLLIMPORT bool enable_partition_pruning;
 extern PGDLLIMPORT bool enable_presorted_aggregate;
 extern PGDLLIMPORT bool enable_async_append;
+extern PGDLLIMPORT bool enable_starjoin_ordering;
 extern PGDLLIMPORT int constraint_exclusion;
 
 extern double index_pages_fetched(double tuples_fetched, BlockNumber pages,
diff --git a/src/include/optimizer/planmain.h b/src/include/optimizer/planmain.h
index c23ab568b98..5669aae7d19 100644
--- a/src/include/optimizer/planmain.h
+++ b/src/include/optimizer/planmain.h
@@ -100,6 +100,7 @@ extern RestrictInfo *build_implied_join_equality(PlannerInfo *root,
 												 Relids qualscope,
 												 Index security_level);
 extern void match_foreign_keys_to_quals(PlannerInfo *root);
+extern void generate_starjoin_clusters(PlannerInfo *root);
 
 /*
  * prototypes for plan/analyzejoins.c
diff --git a/src/test/regress/expected/join.out b/src/test/regress/expected/join.out
index 526430a5ea0..1aeb8d1cbc8 100644
--- a/src/test/regress/expected/join.out
+++ b/src/test/regress/expected/join.out
@@ -13319,3 +13319,62 @@ WHERE s.x = s.c;
 (1 row)
 
 ROLLBACK;
+--
+-- Star-join collapse: FK-unique star clusters get a canonical join order
+--
+CREATE TABLE sj_d1 (id int PRIMARY KEY, v text);
+CREATE TABLE sj_d2 (id int PRIMARY KEY, v text);
+CREATE TABLE sj_d3 (id int PRIMARY KEY, v text);
+CREATE TABLE sj_f (
+    id int PRIMARY KEY,
+    d1 int NOT NULL REFERENCES sj_d1,
+    d2 int NOT NULL REFERENCES sj_d2,
+    d3 int NOT NULL REFERENCES sj_d3
+);
+ANALYZE sj_f, sj_d1, sj_d2, sj_d3;
+-- With the collapse enabled (default), the resulting plan must be identical
+-- to the plan produced with the optimization disabled.
+-- join the fact to all three dimensions, GUC on
+SET enable_starjoin_ordering = on;
+EXPLAIN (COSTS OFF)
+SELECT * FROM sj_f
+  JOIN sj_d1 ON sj_f.d1 = sj_d1.id
+  JOIN sj_d2 ON sj_f.d2 = sj_d2.id
+  JOIN sj_d3 ON sj_f.d3 = sj_d3.id;
+                   QUERY PLAN                    
+-------------------------------------------------
+ Nested Loop
+   Join Filter: (sj_d3.id = sj_f.d3)
+   ->  Nested Loop
+         Join Filter: (sj_d2.id = sj_f.d2)
+         ->  Nested Loop
+               Join Filter: (sj_d1.id = sj_f.d1)
+               ->  Seq Scan on sj_f
+               ->  Seq Scan on sj_d1
+         ->  Seq Scan on sj_d2
+   ->  Seq Scan on sj_d3
+(10 rows)
+
+-- same query, GUC off
+SET enable_starjoin_ordering = off;
+EXPLAIN (COSTS OFF)
+SELECT * FROM sj_f
+  JOIN sj_d1 ON sj_f.d1 = sj_d1.id
+  JOIN sj_d2 ON sj_f.d2 = sj_d2.id
+  JOIN sj_d3 ON sj_f.d3 = sj_d3.id;
+                   QUERY PLAN                    
+-------------------------------------------------
+ Nested Loop
+   Join Filter: (sj_d3.id = sj_f.d3)
+   ->  Nested Loop
+         Join Filter: (sj_d2.id = sj_f.d2)
+         ->  Nested Loop
+               Join Filter: (sj_d1.id = sj_f.d1)
+               ->  Seq Scan on sj_f
+               ->  Seq Scan on sj_d1
+         ->  Seq Scan on sj_d2
+   ->  Seq Scan on sj_d3
+(10 rows)
+
+RESET enable_starjoin_ordering;
+DROP TABLE sj_f, sj_d1, sj_d2, sj_d3;
diff --git a/src/test/regress/expected/starjoin_eager.out b/src/test/regress/expected/starjoin_eager.out
new file mode 100644
index 00000000000..1a22d338927
--- /dev/null
+++ b/src/test/regress/expected/starjoin_eager.out
@@ -0,0 +1,187 @@
+--
+-- STARJOIN_EAGER
+-- Test star join ordering combined with eager aggregation
+--
+-- Ignore platform-dependent memory and hash sizing, but retain the
+-- distinction between single-batch and multi-batch hashing.
+CREATE OR REPLACE FUNCTION pg_temp.starjoin_explain(query text) RETURNS SETOF text
+LANGUAGE plpgsql AS $$
+DECLARE
+  ln text;
+BEGIN
+  FOR ln IN EXECUTE
+    'EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, BUFFERS OFF, SUMMARY OFF) ' || query
+  LOOP
+    ln := regexp_replace(ln, '\m\d+kB', 'NkB', 'g');
+    ln := regexp_replace(ln, 'Buckets: \d+', 'Buckets: N');
+    ln := regexp_replace(ln, 'Batches: (?!1\M)\d+', 'Batches: multiple');
+    ln := regexp_replace(ln, ' \(originally \d+\)', '', 'g');
+    RETURN NEXT ln;
+  END LOOP;
+END;
+$$;
+CREATE TABLE starjoin_eager_h1 (id int PRIMARY KEY, v int);
+CREATE TABLE starjoin_eager_h2 (id int PRIMARY KEY, v int);
+CREATE TABLE starjoin_eager_h3 (id int PRIMARY KEY, v int);
+INSERT INTO starjoin_eager_h1 SELECT i, i % 10 FROM generate_series(1,100) i;
+INSERT INTO starjoin_eager_h2 SELECT i, i FROM generate_series(1,10000) i;
+INSERT INTO starjoin_eager_h3 SELECT i, i FROM generate_series(1,10000) i;
+CREATE TABLE starjoin_eager_hf (id int, d1 int NOT NULL, d2 int NOT NULL, d3 int NOT NULL, x int);
+INSERT INTO starjoin_eager_hf SELECT i, 1 + i % 100, 1 + (i * 7) % 10000, 1 + (i * 13) % 10000, i % 1000
+  FROM generate_series(1,20000) i;
+ALTER TABLE starjoin_eager_hf
+  ADD FOREIGN KEY (d1) REFERENCES starjoin_eager_h1,
+  ADD FOREIGN KEY (d2) REFERENCES starjoin_eager_h2,
+  ADD FOREIGN KEY (d3) REFERENCES starjoin_eager_h3;
+VACUUM ANALYZE starjoin_eager_h1, starjoin_eager_h2,
+               starjoin_eager_h3, starjoin_eager_hf;
+SET max_parallel_workers_per_gather = 0;
+-- With the GUC on, hf is never joined to h2 and h3 before h1, the first
+-- dimension in the canonical order, so the partial aggregation (grouping by
+-- hf.d1) can't be done below the join to h1, unlike with the GUC off.
+-- eager agg, GROUP BY first dim (h1), GUC on
+SET enable_starjoin_ordering = on;
+SELECT pg_temp.starjoin_explain($$
+SELECT h1.v, sum(hf.x)
+FROM starjoin_eager_hf AS hf JOIN starjoin_eager_h1 AS h1 ON hf.d1 = h1.id
+                             JOIN starjoin_eager_h2 AS h2 ON hf.d2 = h2.id
+                             JOIN starjoin_eager_h3 AS h3 ON hf.d3 = h3.id
+GROUP BY h1.v
+$$) AS "QUERY PLAN";
+                                         QUERY PLAN                                          
+---------------------------------------------------------------------------------------------
+ HashAggregate (actual rows=10.00 loops=1)
+   Group Key: h1.v
+   Batches: 1  Memory Usage: NkB
+   ->  Hash Join (actual rows=20000.00 loops=1)
+         Hash Cond: (hf.d3 = h3.id)
+         ->  Hash Join (actual rows=20000.00 loops=1)
+               Hash Cond: (hf.d2 = h2.id)
+               ->  Hash Join (actual rows=20000.00 loops=1)
+                     Hash Cond: (hf.d1 = h1.id)
+                     ->  Seq Scan on starjoin_eager_hf hf (actual rows=20000.00 loops=1)
+                     ->  Hash (actual rows=100.00 loops=1)
+                           Buckets: N  Batches: 1  Memory Usage: NkB
+                           ->  Seq Scan on starjoin_eager_h1 h1 (actual rows=100.00 loops=1)
+               ->  Hash (actual rows=10000.00 loops=1)
+                     Buckets: N  Batches: 1  Memory Usage: NkB
+                     ->  Seq Scan on starjoin_eager_h2 h2 (actual rows=10000.00 loops=1)
+         ->  Hash (actual rows=10000.00 loops=1)
+               Buckets: N  Batches: 1  Memory Usage: NkB
+               ->  Seq Scan on starjoin_eager_h3 h3 (actual rows=10000.00 loops=1)
+(19 rows)
+
+-- eager agg, GROUP BY first dim (h1), GUC off
+SET enable_starjoin_ordering = off;
+SELECT pg_temp.starjoin_explain($$
+SELECT h1.v, sum(hf.x)
+FROM starjoin_eager_hf AS hf JOIN starjoin_eager_h1 AS h1 ON hf.d1 = h1.id
+                             JOIN starjoin_eager_h2 AS h2 ON hf.d2 = h2.id
+                             JOIN starjoin_eager_h3 AS h3 ON hf.d3 = h3.id
+GROUP BY h1.v
+$$) AS "QUERY PLAN";
+                                                QUERY PLAN                                                 
+-----------------------------------------------------------------------------------------------------------
+ Finalize GroupAggregate (actual rows=10.00 loops=1)
+   Group Key: h1.v
+   ->  Sort (actual rows=100.00 loops=1)
+         Sort Key: h1.v
+         Sort Method: quicksort  Memory: NkB
+         ->  Hash Join (actual rows=100.00 loops=1)
+               Hash Cond: (hf.d1 = h1.id)
+               ->  Partial HashAggregate (actual rows=100.00 loops=1)
+                     Group Key: hf.d1
+                     Batches: 1  Memory Usage: NkB
+                     ->  Hash Join (actual rows=20000.00 loops=1)
+                           Hash Cond: (hf.d3 = h3.id)
+                           ->  Hash Join (actual rows=20000.00 loops=1)
+                                 Hash Cond: (hf.d2 = h2.id)
+                                 ->  Seq Scan on starjoin_eager_hf hf (actual rows=20000.00 loops=1)
+                                 ->  Hash (actual rows=10000.00 loops=1)
+                                       Buckets: N  Batches: 1  Memory Usage: NkB
+                                       ->  Seq Scan on starjoin_eager_h2 h2 (actual rows=10000.00 loops=1)
+                           ->  Hash (actual rows=10000.00 loops=1)
+                                 Buckets: N  Batches: 1  Memory Usage: NkB
+                                 ->  Seq Scan on starjoin_eager_h3 h3 (actual rows=10000.00 loops=1)
+               ->  Hash (actual rows=100.00 loops=1)
+                     Buckets: N  Batches: 1  Memory Usage: NkB
+                     ->  Seq Scan on starjoin_eager_h1 h1 (actual rows=100.00 loops=1)
+(24 rows)
+
+-- With h1 last in FROM, and so also last in the canonical order, the partial
+-- aggregation is done below the join to h1 with the GUC on too.
+-- same query, h1 written last in FROM, GUC on
+SET enable_starjoin_ordering = on;
+SELECT pg_temp.starjoin_explain($$
+SELECT h1.v, sum(hf.x)
+FROM starjoin_eager_hf AS hf JOIN starjoin_eager_h2 AS h2 ON hf.d2 = h2.id
+                             JOIN starjoin_eager_h3 AS h3 ON hf.d3 = h3.id
+                             JOIN starjoin_eager_h1 AS h1 ON hf.d1 = h1.id
+GROUP BY h1.v
+$$) AS "QUERY PLAN";
+                                                QUERY PLAN                                                 
+-----------------------------------------------------------------------------------------------------------
+ Finalize GroupAggregate (actual rows=10.00 loops=1)
+   Group Key: h1.v
+   ->  Sort (actual rows=100.00 loops=1)
+         Sort Key: h1.v
+         Sort Method: quicksort  Memory: NkB
+         ->  Hash Join (actual rows=100.00 loops=1)
+               Hash Cond: (hf.d1 = h1.id)
+               ->  Partial HashAggregate (actual rows=100.00 loops=1)
+                     Group Key: hf.d1
+                     Batches: 1  Memory Usage: NkB
+                     ->  Hash Join (actual rows=20000.00 loops=1)
+                           Hash Cond: (hf.d3 = h3.id)
+                           ->  Hash Join (actual rows=20000.00 loops=1)
+                                 Hash Cond: (hf.d2 = h2.id)
+                                 ->  Seq Scan on starjoin_eager_hf hf (actual rows=20000.00 loops=1)
+                                 ->  Hash (actual rows=10000.00 loops=1)
+                                       Buckets: N  Batches: 1  Memory Usage: NkB
+                                       ->  Seq Scan on starjoin_eager_h2 h2 (actual rows=10000.00 loops=1)
+                           ->  Hash (actual rows=10000.00 loops=1)
+                                 Buckets: N  Batches: 1  Memory Usage: NkB
+                                 ->  Seq Scan on starjoin_eager_h3 h3 (actual rows=10000.00 loops=1)
+               ->  Hash (actual rows=100.00 loops=1)
+                     Buckets: N  Batches: 1  Memory Usage: NkB
+                     ->  Seq Scan on starjoin_eager_h1 h1 (actual rows=100.00 loops=1)
+(24 rows)
+
+-- same query, h1 written last in FROM, GUC off
+SET enable_starjoin_ordering = off;
+SELECT pg_temp.starjoin_explain($$
+SELECT h1.v, sum(hf.x)
+FROM starjoin_eager_hf AS hf JOIN starjoin_eager_h2 AS h2 ON hf.d2 = h2.id
+                             JOIN starjoin_eager_h3 AS h3 ON hf.d3 = h3.id
+                             JOIN starjoin_eager_h1 AS h1 ON hf.d1 = h1.id
+GROUP BY h1.v
+$$) AS "QUERY PLAN";
+                                                QUERY PLAN                                                 
+-----------------------------------------------------------------------------------------------------------
+ Finalize GroupAggregate (actual rows=10.00 loops=1)
+   Group Key: h1.v
+   ->  Sort (actual rows=100.00 loops=1)
+         Sort Key: h1.v
+         Sort Method: quicksort  Memory: NkB
+         ->  Hash Join (actual rows=100.00 loops=1)
+               Hash Cond: (hf.d1 = h1.id)
+               ->  Partial HashAggregate (actual rows=100.00 loops=1)
+                     Group Key: hf.d1
+                     Batches: 1  Memory Usage: NkB
+                     ->  Hash Join (actual rows=20000.00 loops=1)
+                           Hash Cond: (hf.d3 = h3.id)
+                           ->  Hash Join (actual rows=20000.00 loops=1)
+                                 Hash Cond: (hf.d2 = h2.id)
+                                 ->  Seq Scan on starjoin_eager_hf hf (actual rows=20000.00 loops=1)
+                                 ->  Hash (actual rows=10000.00 loops=1)
+                                       Buckets: N  Batches: 1  Memory Usage: NkB
+                                       ->  Seq Scan on starjoin_eager_h2 h2 (actual rows=10000.00 loops=1)
+                           ->  Hash (actual rows=10000.00 loops=1)
+                                 Buckets: N  Batches: 1  Memory Usage: NkB
+                                 ->  Seq Scan on starjoin_eager_h3 h3 (actual rows=10000.00 loops=1)
+               ->  Hash (actual rows=100.00 loops=1)
+                     Buckets: N  Batches: 1  Memory Usage: NkB
+                     ->  Seq Scan on starjoin_eager_h1 h1 (actual rows=100.00 loops=1)
+(24 rows)
+
+DROP TABLE starjoin_eager_hf, starjoin_eager_h1, starjoin_eager_h2, starjoin_eager_h3;
diff --git a/src/test/regress/expected/starjoin_eager_large.out b/src/test/regress/expected/starjoin_eager_large.out
new file mode 100644
index 00000000000..15188378ba8
--- /dev/null
+++ b/src/test/regress/expected/starjoin_eager_large.out
@@ -0,0 +1,190 @@
+--
+-- STARJOIN_EAGER_LARGE
+-- Same as starjoin_eager, but with larger tables (expensive)
+--
+-- Ignore platform-dependent memory and hash sizing, but retain the
+-- distinction between single-batch and multi-batch hashing.
+CREATE OR REPLACE FUNCTION pg_temp.starjoin_explain(query text) RETURNS SETOF text
+LANGUAGE plpgsql AS $$
+DECLARE
+  ln text;
+BEGIN
+  FOR ln IN EXECUTE
+    'EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, BUFFERS OFF, SUMMARY OFF) ' || query
+  LOOP
+    ln := regexp_replace(ln, '\m\d+kB', 'NkB', 'g');
+    ln := regexp_replace(ln, 'Buckets: \d+', 'Buckets: N');
+    ln := regexp_replace(ln, 'Batches: (?!1\M)\d+', 'Batches: multiple');
+    ln := regexp_replace(ln, ' \(originally \d+\)', '', 'g');
+    RETURN NEXT ln;
+  END LOOP;
+END;
+$$;
+CREATE TABLE starjoin_eager_h1 (id int PRIMARY KEY, v int);
+CREATE TABLE starjoin_eager_h2 (id int PRIMARY KEY, v int);
+CREATE TABLE starjoin_eager_h3 (id int PRIMARY KEY, v int);
+INSERT INTO starjoin_eager_h1 SELECT i, i % 10 FROM generate_series(1,100) i;
+INSERT INTO starjoin_eager_h2 SELECT i, i FROM generate_series(1,100000) i;
+INSERT INTO starjoin_eager_h3 SELECT i, i FROM generate_series(1,100000) i;
+CREATE TABLE starjoin_eager_hf (id int, d1 int NOT NULL, d2 int NOT NULL, d3 int NOT NULL, x int);
+INSERT INTO starjoin_eager_hf SELECT i, 1 + i % 100, 1 + (i * 7) % 100000, 1 + (i * 13) % 100000, i % 1000
+  FROM generate_series(1,200000) i;
+ALTER TABLE starjoin_eager_hf
+  ADD FOREIGN KEY (d1) REFERENCES starjoin_eager_h1,
+  ADD FOREIGN KEY (d2) REFERENCES starjoin_eager_h2,
+  ADD FOREIGN KEY (d3) REFERENCES starjoin_eager_h3;
+VACUUM ANALYZE starjoin_eager_h1, starjoin_eager_h2,
+               starjoin_eager_h3, starjoin_eager_hf;
+SET max_parallel_workers_per_gather = 0;
+-- Use a small work_mem, so that the hash joins to h2 and h3 need multiple
+-- batches.
+SET work_mem = '400kB';
+-- With the GUC on, hf is never joined to h2 and h3 before h1, the first
+-- dimension in the canonical order, so the partial aggregation (grouping by
+-- hf.d1) can't be done below the join to h1, unlike with the GUC off.
+-- eager agg, GROUP BY first dim (h1), GUC on
+SET enable_starjoin_ordering = on;
+SELECT pg_temp.starjoin_explain($$
+SELECT h1.v, sum(hf.x)
+FROM starjoin_eager_hf AS hf JOIN starjoin_eager_h1 AS h1 ON hf.d1 = h1.id
+                             JOIN starjoin_eager_h2 AS h2 ON hf.d2 = h2.id
+                             JOIN starjoin_eager_h3 AS h3 ON hf.d3 = h3.id
+GROUP BY h1.v
+$$) AS "QUERY PLAN";
+                                         QUERY PLAN                                          
+---------------------------------------------------------------------------------------------
+ HashAggregate (actual rows=10.00 loops=1)
+   Group Key: h1.v
+   Batches: 1  Memory Usage: NkB
+   ->  Hash Join (actual rows=200000.00 loops=1)
+         Hash Cond: (hf.d3 = h3.id)
+         ->  Hash Join (actual rows=200000.00 loops=1)
+               Hash Cond: (hf.d2 = h2.id)
+               ->  Hash Join (actual rows=200000.00 loops=1)
+                     Hash Cond: (hf.d1 = h1.id)
+                     ->  Seq Scan on starjoin_eager_hf hf (actual rows=200000.00 loops=1)
+                     ->  Hash (actual rows=100.00 loops=1)
+                           Buckets: N  Batches: 1  Memory Usage: NkB
+                           ->  Seq Scan on starjoin_eager_h1 h1 (actual rows=100.00 loops=1)
+               ->  Hash (actual rows=100000.00 loops=1)
+                     Buckets: N  Batches: multiple  Memory Usage: NkB
+                     ->  Seq Scan on starjoin_eager_h2 h2 (actual rows=100000.00 loops=1)
+         ->  Hash (actual rows=100000.00 loops=1)
+               Buckets: N  Batches: multiple  Memory Usage: NkB
+               ->  Seq Scan on starjoin_eager_h3 h3 (actual rows=100000.00 loops=1)
+(19 rows)
+
+-- eager agg, GROUP BY first dim (h1), GUC off
+SET enable_starjoin_ordering = off;
+SELECT pg_temp.starjoin_explain($$
+SELECT h1.v, sum(hf.x)
+FROM starjoin_eager_hf AS hf JOIN starjoin_eager_h1 AS h1 ON hf.d1 = h1.id
+                             JOIN starjoin_eager_h2 AS h2 ON hf.d2 = h2.id
+                             JOIN starjoin_eager_h3 AS h3 ON hf.d3 = h3.id
+GROUP BY h1.v
+$$) AS "QUERY PLAN";
+                                                 QUERY PLAN                                                 
+------------------------------------------------------------------------------------------------------------
+ Finalize GroupAggregate (actual rows=10.00 loops=1)
+   Group Key: h1.v
+   ->  Sort (actual rows=100.00 loops=1)
+         Sort Key: h1.v
+         Sort Method: quicksort  Memory: NkB
+         ->  Hash Join (actual rows=100.00 loops=1)
+               Hash Cond: (hf.d1 = h1.id)
+               ->  Partial HashAggregate (actual rows=100.00 loops=1)
+                     Group Key: hf.d1
+                     Batches: 1  Memory Usage: NkB
+                     ->  Hash Join (actual rows=200000.00 loops=1)
+                           Hash Cond: (hf.d3 = h3.id)
+                           ->  Hash Join (actual rows=200000.00 loops=1)
+                                 Hash Cond: (hf.d2 = h2.id)
+                                 ->  Seq Scan on starjoin_eager_hf hf (actual rows=200000.00 loops=1)
+                                 ->  Hash (actual rows=100000.00 loops=1)
+                                       Buckets: N  Batches: multiple  Memory Usage: NkB
+                                       ->  Seq Scan on starjoin_eager_h2 h2 (actual rows=100000.00 loops=1)
+                           ->  Hash (actual rows=100000.00 loops=1)
+                                 Buckets: N  Batches: multiple  Memory Usage: NkB
+                                 ->  Seq Scan on starjoin_eager_h3 h3 (actual rows=100000.00 loops=1)
+               ->  Hash (actual rows=100.00 loops=1)
+                     Buckets: N  Batches: 1  Memory Usage: NkB
+                     ->  Seq Scan on starjoin_eager_h1 h1 (actual rows=100.00 loops=1)
+(24 rows)
+
+-- With h1 last in FROM, and so also last in the canonical order, the partial
+-- aggregation is done below the join to h1 with the GUC on too.
+-- same query, h1 written last in FROM, GUC on
+SET enable_starjoin_ordering = on;
+SELECT pg_temp.starjoin_explain($$
+SELECT h1.v, sum(hf.x)
+FROM starjoin_eager_hf AS hf JOIN starjoin_eager_h2 AS h2 ON hf.d2 = h2.id
+                             JOIN starjoin_eager_h3 AS h3 ON hf.d3 = h3.id
+                             JOIN starjoin_eager_h1 AS h1 ON hf.d1 = h1.id
+GROUP BY h1.v
+$$) AS "QUERY PLAN";
+                                                 QUERY PLAN                                                 
+------------------------------------------------------------------------------------------------------------
+ Finalize GroupAggregate (actual rows=10.00 loops=1)
+   Group Key: h1.v
+   ->  Sort (actual rows=100.00 loops=1)
+         Sort Key: h1.v
+         Sort Method: quicksort  Memory: NkB
+         ->  Hash Join (actual rows=100.00 loops=1)
+               Hash Cond: (hf.d1 = h1.id)
+               ->  Partial HashAggregate (actual rows=100.00 loops=1)
+                     Group Key: hf.d1
+                     Batches: 1  Memory Usage: NkB
+                     ->  Hash Join (actual rows=200000.00 loops=1)
+                           Hash Cond: (hf.d3 = h3.id)
+                           ->  Hash Join (actual rows=200000.00 loops=1)
+                                 Hash Cond: (hf.d2 = h2.id)
+                                 ->  Seq Scan on starjoin_eager_hf hf (actual rows=200000.00 loops=1)
+                                 ->  Hash (actual rows=100000.00 loops=1)
+                                       Buckets: N  Batches: multiple  Memory Usage: NkB
+                                       ->  Seq Scan on starjoin_eager_h2 h2 (actual rows=100000.00 loops=1)
+                           ->  Hash (actual rows=100000.00 loops=1)
+                                 Buckets: N  Batches: multiple  Memory Usage: NkB
+                                 ->  Seq Scan on starjoin_eager_h3 h3 (actual rows=100000.00 loops=1)
+               ->  Hash (actual rows=100.00 loops=1)
+                     Buckets: N  Batches: 1  Memory Usage: NkB
+                     ->  Seq Scan on starjoin_eager_h1 h1 (actual rows=100.00 loops=1)
+(24 rows)
+
+-- same query, h1 written last in FROM, GUC off
+SET enable_starjoin_ordering = off;
+SELECT pg_temp.starjoin_explain($$
+SELECT h1.v, sum(hf.x)
+FROM starjoin_eager_hf AS hf JOIN starjoin_eager_h2 AS h2 ON hf.d2 = h2.id
+                             JOIN starjoin_eager_h3 AS h3 ON hf.d3 = h3.id
+                             JOIN starjoin_eager_h1 AS h1 ON hf.d1 = h1.id
+GROUP BY h1.v
+$$) AS "QUERY PLAN";
+                                                 QUERY PLAN                                                 
+------------------------------------------------------------------------------------------------------------
+ Finalize GroupAggregate (actual rows=10.00 loops=1)
+   Group Key: h1.v
+   ->  Sort (actual rows=100.00 loops=1)
+         Sort Key: h1.v
+         Sort Method: quicksort  Memory: NkB
+         ->  Hash Join (actual rows=100.00 loops=1)
+               Hash Cond: (hf.d1 = h1.id)
+               ->  Partial HashAggregate (actual rows=100.00 loops=1)
+                     Group Key: hf.d1
+                     Batches: 1  Memory Usage: NkB
+                     ->  Hash Join (actual rows=200000.00 loops=1)
+                           Hash Cond: (hf.d3 = h3.id)
+                           ->  Hash Join (actual rows=200000.00 loops=1)
+                                 Hash Cond: (hf.d2 = h2.id)
+                                 ->  Seq Scan on starjoin_eager_hf hf (actual rows=200000.00 loops=1)
+                                 ->  Hash (actual rows=100000.00 loops=1)
+                                       Buckets: N  Batches: multiple  Memory Usage: NkB
+                                       ->  Seq Scan on starjoin_eager_h2 h2 (actual rows=100000.00 loops=1)
+                           ->  Hash (actual rows=100000.00 loops=1)
+                                 Buckets: N  Batches: multiple  Memory Usage: NkB
+                                 ->  Seq Scan on starjoin_eager_h3 h3 (actual rows=100000.00 loops=1)
+               ->  Hash (actual rows=100.00 loops=1)
+                     Buckets: N  Batches: 1  Memory Usage: NkB
+                     ->  Seq Scan on starjoin_eager_h1 h1 (actual rows=100.00 loops=1)
+(24 rows)
+
+DROP TABLE starjoin_eager_hf, starjoin_eager_h1, starjoin_eager_h2, starjoin_eager_h3;
diff --git a/src/test/regress/expected/starjoin_other.out b/src/test/regress/expected/starjoin_other.out
new file mode 100644
index 00000000000..f6fe849430b
--- /dev/null
+++ b/src/test/regress/expected/starjoin_other.out
@@ -0,0 +1,444 @@
+--
+-- Checks for various other cases with enable_starjoin_ordering (the
+-- planning failures are covered by starjoin_reproducers).
+--
+-- Each check is a single boolean, so that the output does not depend on
+-- platform-specific costs or memory usage.  Some checks show known
+-- limitations, where the plan with the GUC enabled is worse.
+--
+-- Some checks are about the planning effort (the number of join rels the
+-- join search builds), which is not visible in SQL.  Those checks compare the
+-- planner memory usage reported by EXPLAIN (MEMORY), which is proportional
+-- to the number of join rels and paths.
+--
+SET max_parallel_workers_per_gather = 0;
+-- total cost of the plan, with enable_starjoin_ordering enabled/disabled
+CREATE FUNCTION starjoin_other_cost(query text, starjoin bool) RETURNS float8
+LANGUAGE plpgsql AS $$
+DECLARE
+  plan json;
+BEGIN
+  PERFORM set_config('enable_starjoin_ordering', starjoin::text, true);
+  EXECUTE 'EXPLAIN (FORMAT JSON) ' || query INTO plan;
+  RETURN (plan->0->'Plan'->>'Total Cost')::float8;
+END;
+$$;
+-- memory used by the planner (in kB), with enable_starjoin_ordering
+-- enabled/disabled
+CREATE FUNCTION starjoin_other_memory(query text, starjoin bool) RETURNS bigint
+LANGUAGE plpgsql AS $$
+DECLARE
+  plan json;
+BEGIN
+  PERFORM set_config('enable_starjoin_ordering', starjoin::text, true);
+  EXECUTE 'EXPLAIN (MEMORY, FORMAT JSON) ' || query INTO plan;
+  RETURN (plan->0->'Planning'->>'Memory Used')::bigint;
+END;
+$$;
+-- the plan (without costs), with enable_starjoin_ordering enabled/disabled
+CREATE FUNCTION starjoin_other_plan(query text, starjoin bool) RETURNS text
+LANGUAGE plpgsql AS $$
+DECLARE
+  plan json;
+BEGIN
+  PERFORM set_config('enable_starjoin_ordering', starjoin::text, true);
+  EXECUTE 'EXPLAIN (COSTS OFF, FORMAT JSON) ' || query INTO plan;
+  RETURN plan::text;
+END;
+$$;
+-- star with 3 dimensions (same as in starjoin_plan)
+CREATE TABLE starjoin_other_p1 (id int PRIMARY KEY, v int, w int) WITH (autovacuum_enabled = off);
+CREATE TABLE starjoin_other_p2 (id int PRIMARY KEY, v int, w int) WITH (autovacuum_enabled = off);
+CREATE TABLE starjoin_other_p3 (id int PRIMARY KEY, v int, w int) WITH (autovacuum_enabled = off);
+INSERT INTO starjoin_other_p1 SELECT i, i % 100, i FROM generate_series(1, 1000) i;
+INSERT INTO starjoin_other_p2 SELECT i, i % 100, i FROM generate_series(1, 1000) i;
+INSERT INTO starjoin_other_p3 SELECT i, i % 100, i FROM generate_series(1, 1000) i;
+CREATE TABLE starjoin_other_pf (id int PRIMARY KEY, d1 int NOT NULL,
+  d2 int NOT NULL, d3 int NOT NULL, x int) WITH (autovacuum_enabled = off);
+INSERT INTO starjoin_other_pf
+SELECT i, 1 + (i * 7) % 1000, 1 + (i * 13) % 1000, 1 + (i * 17) % 1000, i % 1000
+  FROM generate_series(1, 20000) i;
+-- add the foreign keys after loading the data (faster than checking each row)
+ALTER TABLE starjoin_other_pf
+  ADD FOREIGN KEY (d1) REFERENCES starjoin_other_p1,
+  ADD FOREIGN KEY (d2) REFERENCES starjoin_other_p2,
+  ADD FOREIGN KEY (d3) REFERENCES starjoin_other_p3;
+-- star with two wide dimensions and a large narrow one (same as in
+-- starjoin_width)
+CREATE TABLE starjoin_other_wa (id int PRIMARY KEY, t text) WITH (autovacuum_enabled = off);
+CREATE TABLE starjoin_other_wb (id int PRIMARY KEY, t text) WITH (autovacuum_enabled = off);
+CREATE TABLE starjoin_other_wc (id int PRIMARY KEY, v int) WITH (autovacuum_enabled = off);
+INSERT INTO starjoin_other_wa SELECT i, repeat(md5(i::text), 16) FROM generate_series(1, 100) i;
+INSERT INTO starjoin_other_wb SELECT i, repeat(md5(i::text), 16) FROM generate_series(1, 100) i;
+INSERT INTO starjoin_other_wc SELECT i, i FROM generate_series(1, 10000) i;
+CREATE TABLE starjoin_other_wf (id int, a int NOT NULL, b int NOT NULL,
+  c int NOT NULL) WITH (autovacuum_enabled = off);
+INSERT INTO starjoin_other_wf
+SELECT i, 1 + i % 100, 1 + (i * 7) % 100, 1 + (i * 13) % 10000
+  FROM generate_series(1, 10000) i;
+ALTER TABLE starjoin_other_wf
+  ADD FOREIGN KEY (a) REFERENCES starjoin_other_wa,
+  ADD FOREIGN KEY (b) REFERENCES starjoin_other_wb,
+  ADD FOREIGN KEY (c) REFERENCES starjoin_other_wc;
+-- star with a small dimension used in GROUP BY (same as in starjoin_eager)
+CREATE TABLE starjoin_other_h1 (id int PRIMARY KEY, v int) WITH (autovacuum_enabled = off);
+CREATE TABLE starjoin_other_h2 (id int PRIMARY KEY, v int) WITH (autovacuum_enabled = off);
+CREATE TABLE starjoin_other_h3 (id int PRIMARY KEY, v int) WITH (autovacuum_enabled = off);
+INSERT INTO starjoin_other_h1 SELECT i, i % 10 FROM generate_series(1, 100) i;
+INSERT INTO starjoin_other_h2 SELECT i, i FROM generate_series(1, 10000) i;
+INSERT INTO starjoin_other_h3 SELECT i, i FROM generate_series(1, 10000) i;
+CREATE TABLE starjoin_other_hf (id int, d1 int NOT NULL, d2 int NOT NULL,
+  d3 int NOT NULL, x int) WITH (autovacuum_enabled = off);
+INSERT INTO starjoin_other_hf
+SELECT i, 1 + i % 100, 1 + (i * 7) % 10000, 1 + (i * 13) % 10000, i % 1000
+  FROM generate_series(1, 20000) i;
+ALTER TABLE starjoin_other_hf
+  ADD FOREIGN KEY (d1) REFERENCES starjoin_other_h1,
+  ADD FOREIGN KEY (d2) REFERENCES starjoin_other_h2,
+  ADD FOREIGN KEY (d3) REFERENCES starjoin_other_h3;
+-- star with 10 dimensions d1-d10, a table "a" referenced by the fact, and 8
+-- tables c1-c8 joined on a non-unique column (all in the same equivalence
+-- class, so each pair of them can be joined)
+CREATE TABLE starjoin_other_a (id int PRIMARY KEY, v int) WITH (autovacuum_enabled = off);
+INSERT INTO starjoin_other_a SELECT i, i FROM generate_series(1, 100) i;
+DO $$
+BEGIN
+  FOR i IN 1..10 LOOP
+    EXECUTE format('CREATE TABLE starjoin_other_d%s (id int PRIMARY KEY, v int) WITH (autovacuum_enabled = off)', i);
+    EXECUTE format('INSERT INTO starjoin_other_d%s SELECT i, i FROM generate_series(1, 100) i', i);
+  END LOOP;
+  FOR i IN 1..8 LOOP
+    EXECUTE format('CREATE TABLE starjoin_other_c%s (id int PRIMARY KEY, v int) WITH (autovacuum_enabled = off)', i);
+    EXECUTE format('INSERT INTO starjoin_other_c%s SELECT i, i %% 50 FROM generate_series(1, 100) i', i);
+  END LOOP;
+END;
+$$;
+CREATE TABLE starjoin_other_f (id int PRIMARY KEY, a int NOT NULL,
+  d1 int NOT NULL, d2 int NOT NULL, d3 int NOT NULL, d4 int NOT NULL,
+  d5 int NOT NULL, d6 int NOT NULL, d7 int NOT NULL, d8 int NOT NULL,
+  d9 int NOT NULL, d10 int NOT NULL) WITH (autovacuum_enabled = off);
+INSERT INTO starjoin_other_f
+SELECT i, 1 + i % 100, 1 + (i * 3) % 100, 1 + (i * 7) % 100, 1 + (i * 11) % 100,
+       1 + (i * 13) % 100, 1 + (i * 17) % 100, 1 + (i * 19) % 100,
+       1 + (i * 23) % 100, 1 + (i * 29) % 100, 1 + (i * 31) % 100,
+       1 + (i * 37) % 100
+  FROM generate_series(1, 1000) i;
+ALTER TABLE starjoin_other_f
+  ADD FOREIGN KEY (a) REFERENCES starjoin_other_a,
+  ADD FOREIGN KEY (d1) REFERENCES starjoin_other_d1,
+  ADD FOREIGN KEY (d2) REFERENCES starjoin_other_d2,
+  ADD FOREIGN KEY (d3) REFERENCES starjoin_other_d3,
+  ADD FOREIGN KEY (d4) REFERENCES starjoin_other_d4,
+  ADD FOREIGN KEY (d5) REFERENCES starjoin_other_d5,
+  ADD FOREIGN KEY (d6) REFERENCES starjoin_other_d6,
+  ADD FOREIGN KEY (d7) REFERENCES starjoin_other_d7,
+  ADD FOREIGN KEY (d8) REFERENCES starjoin_other_d8,
+  ADD FOREIGN KEY (d9) REFERENCES starjoin_other_d9,
+  ADD FOREIGN KEY (d10) REFERENCES starjoin_other_d10;
+VACUUM ANALYZE starjoin_other_p1, starjoin_other_p2, starjoin_other_p3,
+  starjoin_other_pf, starjoin_other_wa, starjoin_other_wb, starjoin_other_wc,
+  starjoin_other_wf, starjoin_other_h1, starjoin_other_h2, starjoin_other_h3,
+  starjoin_other_hf, starjoin_other_a, starjoin_other_d1, starjoin_other_d2,
+  starjoin_other_d3, starjoin_other_d4, starjoin_other_d5, starjoin_other_d6,
+  starjoin_other_d7, starjoin_other_d8, starjoin_other_d9, starjoin_other_d10,
+  starjoin_other_c1, starjoin_other_c2, starjoin_other_c3, starjoin_other_c4,
+  starjoin_other_c5, starjoin_other_c6, starjoin_other_c7, starjoin_other_c8,
+  starjoin_other_f;
+--
+-- Extra (non-FK) join clause between the fact and a dimension
+--
+-- The canonical order relies on each join to a dimension preserving the
+-- cardinality of the fact, so that all join orders of a cluster produce the
+-- same row counts.  But an additional join clause between the fact and the
+-- dimension (not matching the foreign key) makes the join selective, so the
+-- dimension should be joined first.  The cluster conditions check join
+-- clauses to other rels, but not additional join clauses to the fact.
+--
+SELECT $$
+SELECT count(*) FROM starjoin_other_pf AS pf
+  JOIN starjoin_other_p1 AS p1 ON pf.d1 = p1.id
+  JOIN starjoin_other_p2 AS p2 ON pf.d2 = p2.id
+  JOIN starjoin_other_p3 AS p3 ON pf.d3 = p3.id AND pf.x = p3.w
+$$ AS q_extra_clause \gset
+-- the canonical order joins p3 last, so the plan with the GUC enabled is
+-- more expensive
+SELECT starjoin_other_cost(:'q_extra_clause', true)
+       > starjoin_other_cost(:'q_extra_clause', false) * 1.01 AS extra_clause_cost_higher;
+ extra_clause_cost_higher 
+--------------------------
+ t
+(1 row)
+
+--
+-- OR clause, from which extract_restriction_or_clauses() derives a
+-- restriction on the dimension, which excludes the dimension from the
+-- cluster (the clusters are built after extracting the restrictions)
+--
+SELECT $$
+SELECT count(*) FROM starjoin_other_pf AS pf
+  JOIN starjoin_other_p1 AS p1 ON pf.d1 = p1.id
+  JOIN starjoin_other_p2 AS p2 ON pf.d2 = p2.id
+  JOIN starjoin_other_p3 AS p3 ON pf.d3 = p3.id
+ WHERE (p3.w = 1 AND pf.x = 1) OR (p3.w = 2 AND pf.x = 2)
+$$ AS q_or_clause \gset
+SELECT starjoin_other_cost(:'q_or_clause', true)
+       <= starjoin_other_cost(:'q_or_clause', false) * 1.01 AS or_clause_cost_ok;
+ or_clause_cost_ok 
+-------------------
+ t
+(1 row)
+
+--
+-- Pure FK joins, with dimensions of very different widths
+--
+-- Even if all joins preserve the cardinality, the join orders don't have the
+-- same cost.  With a small work_mem the hash join to the large dimension (wc)
+-- needs multiple batches, and the cost of batching depends on the width of
+-- the outer rows.  So it's much cheaper to join wc before the two wide
+-- dimensions, but wc is the last one in the canonical order.
+--
+SELECT $$
+SELECT wa.t, wb.t, wc.v FROM starjoin_other_wf AS wf
+  JOIN starjoin_other_wa AS wa ON wf.a = wa.id
+  JOIN starjoin_other_wb AS wb ON wf.b = wb.id
+  JOIN starjoin_other_wc AS wc ON wf.c = wc.id
+$$ AS q_width \gset
+-- Use 128kB, so that the hash join to wc needs multiple batches on all
+-- platforms.  With 256kB that's barely the case on 64-bit platforms (the
+-- hash table fits with work_mem of about 268kB), and not at all on 32-bit
+-- platforms, where the hash tuples are smaller and the hash table fits with
+-- less than 200kB.
+SET work_mem = '128kB';
+-- the canonical order joins wc last, so the plan with the GUC enabled is
+-- more expensive
+SELECT starjoin_other_cost(:'q_width', true)
+       > starjoin_other_cost(:'q_width', false) * 1.01 AS width_cost_higher;
+ width_cost_higher 
+-------------------
+ t
+(1 row)
+
+RESET work_mem;
+--
+-- Canonical pruning
+--
+-- Joins where one side has no cluster dimensions are not checked, so the
+-- join search still builds the 2-way joins of the fact with each dimension,
+-- and (fact, d2) + d1 passes the check too.  For the star with 10 dimensions
+-- the search builds 19 join rels instead of the 10 in the canonical order.
+-- Compare to planning the canonical order directly, forced by
+-- join_collapse_limit = 1 (the plans are the same).
+--
+SELECT $$
+SELECT count(*) FROM starjoin_other_f AS f
+  JOIN starjoin_other_d1 AS d1 ON f.d1 = d1.id
+  JOIN starjoin_other_d2 AS d2 ON f.d2 = d2.id
+  JOIN starjoin_other_d3 AS d3 ON f.d3 = d3.id
+  JOIN starjoin_other_d4 AS d4 ON f.d4 = d4.id
+  JOIN starjoin_other_d5 AS d5 ON f.d5 = d5.id
+  JOIN starjoin_other_d6 AS d6 ON f.d6 = d6.id
+  JOIN starjoin_other_d7 AS d7 ON f.d7 = d7.id
+  JOIN starjoin_other_d8 AS d8 ON f.d8 = d8.id
+  JOIN starjoin_other_d9 AS d9 ON f.d9 = d9.id
+  JOIN starjoin_other_d10 AS d10 ON f.d10 = d10.id
+$$ AS q_star \gset
+SET join_collapse_limit = 1;
+SELECT starjoin_other_plan(:'q_star', true) AS plan_canonical,
+       starjoin_other_memory(:'q_star', true) AS memory_canonical \gset
+-- a single subproblem with 11 rels (below geqo_threshold)
+SET join_collapse_limit = 20;
+SELECT starjoin_other_plan(:'q_star', true) = :'plan_canonical' AS flat_plan_canonical;
+ flat_plan_canonical 
+---------------------
+ t
+(1 row)
+
+-- XXX the search uses more memory than planning the canonical order
+SELECT starjoin_other_memory(:'q_star', true) <= :memory_canonical * 1.1 AS flat_search_canonical;
+ flat_search_canonical 
+-----------------------
+ f
+(1 row)
+
+RESET join_collapse_limit;
+--
+-- Outer joins and semijoins
+--
+-- Dimensions must not be part of any SpecialJoinInfo, but the check considers
+-- the syntactic relids (syn_lefthand/syn_righthand), not only the minimal
+-- ones.  So a LEFT JOIN or a semijoin (EXISTS) placed after the star joins
+-- disables the optimization, even if it references only the fact.  Writing
+-- the LEFT JOIN first works.  Each query has 8 rels (a single subproblem), and
+-- with the optimization the join search needs much less memory.
+--
+SELECT $$
+SELECT count(a.v) FROM starjoin_other_f AS f
+  LEFT JOIN starjoin_other_a AS a ON f.a = a.id
+  JOIN starjoin_other_d1 AS d1 ON f.d1 = d1.id
+  JOIN starjoin_other_d2 AS d2 ON f.d2 = d2.id
+  JOIN starjoin_other_d3 AS d3 ON f.d3 = d3.id
+  JOIN starjoin_other_d4 AS d4 ON f.d4 = d4.id
+  JOIN starjoin_other_d5 AS d5 ON f.d5 = d5.id
+  JOIN starjoin_other_d6 AS d6 ON f.d6 = d6.id
+$$ AS q_left_join_first \gset
+SELECT $$
+SELECT count(a.v) FROM starjoin_other_f AS f
+  JOIN starjoin_other_d1 AS d1 ON f.d1 = d1.id
+  JOIN starjoin_other_d2 AS d2 ON f.d2 = d2.id
+  JOIN starjoin_other_d3 AS d3 ON f.d3 = d3.id
+  JOIN starjoin_other_d4 AS d4 ON f.d4 = d4.id
+  JOIN starjoin_other_d5 AS d5 ON f.d5 = d5.id
+  JOIN starjoin_other_d6 AS d6 ON f.d6 = d6.id
+  LEFT JOIN starjoin_other_a AS a ON f.a = a.id
+$$ AS q_left_join_last \gset
+SELECT $$
+SELECT count(*) FROM starjoin_other_f AS f
+  JOIN starjoin_other_d1 AS d1 ON f.d1 = d1.id
+  JOIN starjoin_other_d2 AS d2 ON f.d2 = d2.id
+  JOIN starjoin_other_d3 AS d3 ON f.d3 = d3.id
+  JOIN starjoin_other_d4 AS d4 ON f.d4 = d4.id
+  JOIN starjoin_other_d5 AS d5 ON f.d5 = d5.id
+  JOIN starjoin_other_d6 AS d6 ON f.d6 = d6.id
+ WHERE EXISTS (SELECT 1 FROM starjoin_other_a AS a WHERE a.v = f.a)
+$$ AS q_exists \gset
+SELECT starjoin_other_memory(:'q_left_join_first', true)
+       < starjoin_other_memory(:'q_left_join_first', false) * 0.5 AS left_join_first_pruned;
+ left_join_first_pruned 
+------------------------
+ t
+(1 row)
+
+-- XXX no pruning with the LEFT JOIN at the end
+SELECT starjoin_other_memory(:'q_left_join_last', true)
+       < starjoin_other_memory(:'q_left_join_last', false) * 0.5 AS left_join_last_pruned;
+ left_join_last_pruned 
+-----------------------
+ f
+(1 row)
+
+-- XXX no pruning with a semijoin
+SELECT starjoin_other_memory(:'q_exists', true)
+       < starjoin_other_memory(:'q_exists', false) * 0.5 AS exists_pruned;
+ exists_pruned 
+---------------
+ f
+(1 row)
+
+--
+-- Star split into subproblems
+--
+-- With the default join_collapse_limit, the star with 10 dimensions is split
+-- into two subproblems, and the canonical order is enforced in both.
+--
+SELECT starjoin_other_memory(:'q_star', true)
+       < starjoin_other_memory(:'q_star', false) * 0.5 AS split_search_pruned;
+ split_search_pruned 
+---------------------
+ t
+(1 row)
+
+--
+-- GEQO
+--
+-- The canonical order is enforced by GEQO too.
+--
+SET join_collapse_limit = 20;
+SET geqo_threshold = 8;
+-- GEQO uses the canonical order
+SELECT starjoin_other_plan(:'q_star', true) = :'plan_canonical' AS geqo_plan_canonical;
+ geqo_plan_canonical 
+---------------------
+ t
+(1 row)
+
+RESET geqo_threshold;
+RESET join_collapse_limit;
+--
+-- Overhead in subproblems unrelated to the star
+--
+-- If the query has a cluster, the canonical order is checked for each join in
+-- all subproblems, including a large separate subproblem (8 rels joinable in
+-- any order).  With only two dimensions there's nothing to prune in the star,
+-- so the planning should not use more memory with the GUC enabled (e.g. if
+-- the check leaked memory).
+--
+SELECT $$
+SELECT count(*)
+  FROM (starjoin_other_f AS f
+        JOIN starjoin_other_d1 AS d1 ON f.d1 = d1.id
+        JOIN starjoin_other_d2 AS d2 ON f.d2 = d2.id)
+  JOIN (starjoin_other_c1 AS c1
+        JOIN starjoin_other_c2 AS c2 ON c1.v = c2.v
+        JOIN starjoin_other_c3 AS c3 ON c2.v = c3.v
+        JOIN starjoin_other_c4 AS c4 ON c3.v = c4.v
+        JOIN starjoin_other_c5 AS c5 ON c4.v = c5.v
+        JOIN starjoin_other_c6 AS c6 ON c5.v = c6.v
+        JOIN starjoin_other_c7 AS c7 ON c6.v = c7.v
+        JOIN starjoin_other_c8 AS c8 ON c7.v = c8.v) ON f.id = c1.id
+$$ AS q_subproblems \gset
+SELECT starjoin_other_memory(:'q_subproblems', true)
+       <= starjoin_other_memory(:'q_subproblems', false) * 1.01 AS subproblems_memory_ok;
+ subproblems_memory_ok 
+-----------------------
+ t
+(1 row)
+
+--
+-- Eager aggregation
+--
+-- With GROUP BY on a column of a dimension (h1), eager aggregation can place
+-- a partial aggregate on the join of the fact and the other dimensions, and
+-- then join h1.  With the canonical order that join rel is only built if h1
+-- is the last dimension, so the plan depends on the order of the dimensions
+-- in the FROM clause.
+--
+SELECT $$
+SELECT h1.v, sum(hf.x) FROM starjoin_other_hf AS hf
+  JOIN starjoin_other_h1 AS h1 ON hf.d1 = h1.id
+  JOIN starjoin_other_h2 AS h2 ON hf.d2 = h2.id
+  JOIN starjoin_other_h3 AS h3 ON hf.d3 = h3.id
+ GROUP BY h1.v
+$$ AS q_eager_first \gset
+SELECT $$
+SELECT h1.v, sum(hf.x) FROM starjoin_other_hf AS hf
+  JOIN starjoin_other_h2 AS h2 ON hf.d2 = h2.id
+  JOIN starjoin_other_h3 AS h3 ON hf.d3 = h3.id
+  JOIN starjoin_other_h1 AS h1 ON hf.d1 = h1.id
+ GROUP BY h1.v
+$$ AS q_eager_last \gset
+SELECT starjoin_other_plan(:'q_eager_first', false)
+       LIKE '%"Partial Mode": "Partial"%' AS eager_first_partial_agg_off;
+ eager_first_partial_agg_off 
+-----------------------------
+ t
+(1 row)
+
+-- the canonical order joins h1 first, so there's no partial aggregate with
+-- the GUC enabled
+SELECT starjoin_other_plan(:'q_eager_first', true)
+       LIKE '%"Partial Mode": "Partial"%' AS eager_first_partial_agg_on;
+ eager_first_partial_agg_on 
+----------------------------
+ f
+(1 row)
+
+SELECT starjoin_other_plan(:'q_eager_last', true)
+       LIKE '%"Partial Mode": "Partial"%' AS eager_last_partial_agg_on;
+ eager_last_partial_agg_on 
+---------------------------
+ t
+(1 row)
+
+RESET max_parallel_workers_per_gather;
+DROP FUNCTION starjoin_other_cost(text, bool);
+DROP FUNCTION starjoin_other_memory(text, bool);
+DROP FUNCTION starjoin_other_plan(text, bool);
+DROP TABLE starjoin_other_pf, starjoin_other_p1, starjoin_other_p2,
+  starjoin_other_p3, starjoin_other_wf, starjoin_other_wa, starjoin_other_wb,
+  starjoin_other_wc, starjoin_other_hf, starjoin_other_h1, starjoin_other_h2,
+  starjoin_other_h3, starjoin_other_f, starjoin_other_a, starjoin_other_d1,
+  starjoin_other_d2, starjoin_other_d3, starjoin_other_d4, starjoin_other_d5,
+  starjoin_other_d6, starjoin_other_d7, starjoin_other_d8, starjoin_other_d9,
+  starjoin_other_d10, starjoin_other_c1, starjoin_other_c2, starjoin_other_c3,
+  starjoin_other_c4, starjoin_other_c5, starjoin_other_c6, starjoin_other_c7,
+  starjoin_other_c8;
diff --git a/src/test/regress/expected/starjoin_plan.out b/src/test/regress/expected/starjoin_plan.out
new file mode 100644
index 00000000000..88745c94bbd
--- /dev/null
+++ b/src/test/regress/expected/starjoin_plan.out
@@ -0,0 +1,172 @@
+--
+-- STARJOIN_PLAN
+-- Test star join ordering with extra join quals between fact and dimension
+--
+-- Ignore platform-dependent memory and hash sizing, but retain the
+-- distinction between single-batch and multi-batch hashing.
+CREATE OR REPLACE FUNCTION pg_temp.starjoin_explain(query text) RETURNS SETOF text
+LANGUAGE plpgsql AS $$
+DECLARE
+  ln text;
+BEGIN
+  FOR ln IN EXECUTE
+    'EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, BUFFERS OFF, SUMMARY OFF) ' || query
+  LOOP
+    ln := regexp_replace(ln, '\m\d+kB', 'NkB', 'g');
+    ln := regexp_replace(ln, 'Buckets: \d+', 'Buckets: N');
+    ln := regexp_replace(ln, 'Batches: (?!1\M)\d+', 'Batches: multiple');
+    ln := regexp_replace(ln, ' \(originally \d+\)', '', 'g');
+    RETURN NEXT ln;
+  END LOOP;
+END;
+$$;
+CREATE TABLE starjoin_plan_p1 (id int PRIMARY KEY, v int, w int);
+CREATE TABLE starjoin_plan_p2 (id int PRIMARY KEY, v int, w int);
+CREATE TABLE starjoin_plan_p3 (id int PRIMARY KEY, v int, w int);
+INSERT INTO starjoin_plan_p1 SELECT i, i % 100, i FROM generate_series(1,1000) i;
+INSERT INTO starjoin_plan_p2 SELECT i, i % 100, i FROM generate_series(1,1000) i;
+INSERT INTO starjoin_plan_p3 SELECT i, i % 100, i FROM generate_series(1,1000) i;
+CREATE TABLE starjoin_plan_pf (id int PRIMARY KEY,
+  d1 int NOT NULL REFERENCES starjoin_plan_p1,
+  d2 int NOT NULL REFERENCES starjoin_plan_p2,
+  d3 int NOT NULL REFERENCES starjoin_plan_p3,
+  x int);
+INSERT INTO starjoin_plan_pf SELECT i, 1 + (i * 7) % 1000, 1 + (i * 13) % 1000, 1 + (i * 17) % 1000, i % 1000
+  FROM generate_series(1,20000) i;
+VACUUM ANALYZE starjoin_plan_p1, starjoin_plan_p2, starjoin_plan_p3, starjoin_plan_pf;
+SET max_parallel_workers_per_gather = 0;
+-- Q1: extra (non-FK) join qual between fact and the last dimension. It makes
+-- the join to p3 selective, but p3 is still a dimension, so with the GUC on
+-- p3 is joined last, while with the GUC off it's joined first.
+-- join the fact to p1, p2 and p3, with an extra join qual for p3, GUC on
+SET enable_starjoin_ordering = on;
+SELECT pg_temp.starjoin_explain($$
+SELECT count(*) FROM starjoin_plan_pf AS pf
+  JOIN starjoin_plan_p1 AS p1 ON pf.d1 = p1.id
+  JOIN starjoin_plan_p2 AS p2 ON pf.d2 = p2.id
+  JOIN starjoin_plan_p3 AS p3 ON pf.d3 = p3.id AND pf.x = p3.w
+$$) AS "QUERY PLAN";
+                                         QUERY PLAN                                          
+---------------------------------------------------------------------------------------------
+ Aggregate (actual rows=1.00 loops=1)
+   ->  Hash Join (actual rows=0.00 loops=1)
+         Hash Cond: ((pf.d3 = p3.id) AND (pf.x = p3.w))
+         ->  Hash Join (actual rows=20000.00 loops=1)
+               Hash Cond: (pf.d2 = p2.id)
+               ->  Hash Join (actual rows=20000.00 loops=1)
+                     Hash Cond: (pf.d1 = p1.id)
+                     ->  Seq Scan on starjoin_plan_pf pf (actual rows=20000.00 loops=1)
+                     ->  Hash (actual rows=1000.00 loops=1)
+                           Buckets: N  Batches: 1  Memory Usage: NkB
+                           ->  Seq Scan on starjoin_plan_p1 p1 (actual rows=1000.00 loops=1)
+               ->  Hash (actual rows=1000.00 loops=1)
+                     Buckets: N  Batches: 1  Memory Usage: NkB
+                     ->  Seq Scan on starjoin_plan_p2 p2 (actual rows=1000.00 loops=1)
+         ->  Hash (actual rows=1000.00 loops=1)
+               Buckets: N  Batches: 1  Memory Usage: NkB
+               ->  Seq Scan on starjoin_plan_p3 p3 (actual rows=1000.00 loops=1)
+(17 rows)
+
+-- same query, GUC off
+SET enable_starjoin_ordering = off;
+SELECT pg_temp.starjoin_explain($$
+SELECT count(*) FROM starjoin_plan_pf AS pf
+  JOIN starjoin_plan_p1 AS p1 ON pf.d1 = p1.id
+  JOIN starjoin_plan_p2 AS p2 ON pf.d2 = p2.id
+  JOIN starjoin_plan_p3 AS p3 ON pf.d3 = p3.id AND pf.x = p3.w
+$$) AS "QUERY PLAN";
+                                              QUERY PLAN                                               
+-------------------------------------------------------------------------------------------------------
+ Aggregate (actual rows=1.00 loops=1)
+   ->  Nested Loop (actual rows=0.00 loops=1)
+         ->  Nested Loop (actual rows=0.00 loops=1)
+               ->  Hash Join (actual rows=0.00 loops=1)
+                     Hash Cond: ((pf.d3 = p3.id) AND (pf.x = p3.w))
+                     ->  Seq Scan on starjoin_plan_pf pf (actual rows=20000.00 loops=1)
+                     ->  Hash (actual rows=1000.00 loops=1)
+                           Buckets: N  Batches: 1  Memory Usage: NkB
+                           ->  Seq Scan on starjoin_plan_p3 p3 (actual rows=1000.00 loops=1)
+               ->  Index Only Scan using starjoin_plan_p1_pkey on starjoin_plan_p1 p1 (never executed)
+                     Index Cond: (id = pf.d1)
+                     Heap Fetches: 0
+                     Index Searches: 0
+         ->  Index Only Scan using starjoin_plan_p2_pkey on starjoin_plan_p2 p2 (never executed)
+               Index Cond: (id = pf.d2)
+               Heap Fetches: 0
+               Index Searches: 0
+(17 rows)
+
+-- Q2: OR clause from which extract_restriction_or_clauses() derives a
+-- restriction on p3, so p3 is not a dimension (the clusters are built after
+-- deriving the restrictions), and the plan is the same as with the GUC off.
+-- join the fact to p1, p2 and p3, with an OR clause in WHERE, GUC on
+SET enable_starjoin_ordering = on;
+SELECT pg_temp.starjoin_explain($$
+SELECT count(*) FROM starjoin_plan_pf AS pf
+  JOIN starjoin_plan_p1 AS p1 ON pf.d1 = p1.id
+  JOIN starjoin_plan_p2 AS p2 ON pf.d2 = p2.id
+  JOIN starjoin_plan_p3 AS p3 ON pf.d3 = p3.id
+ WHERE (p3.w = 1 AND pf.x = 1) OR (p3.w = 2 AND pf.x = 2)
+$$) AS "QUERY PLAN";
+                                                     QUERY PLAN                                                      
+---------------------------------------------------------------------------------------------------------------------
+ Aggregate (actual rows=1.00 loops=1)
+   ->  Nested Loop (actual rows=0.00 loops=1)
+         ->  Nested Loop (actual rows=0.00 loops=1)
+               ->  Nested Loop (actual rows=0.00 loops=1)
+                     Join Filter: ((p3.id = pf.d3) AND (((p3.w = 1) AND (pf.x = 1)) OR ((p3.w = 2) AND (pf.x = 2))))
+                     Rows Removed by Join Filter: 80
+                     ->  Seq Scan on starjoin_plan_pf pf (actual rows=40.00 loops=1)
+                           Filter: ((x = 1) OR (x = 2))
+                           Rows Removed by Filter: 19960
+                     ->  Materialize (actual rows=2.00 loops=40)
+                           Storage: Memory  Maximum Storage: NkB
+                           ->  Seq Scan on starjoin_plan_p3 p3 (actual rows=2.00 loops=1)
+                                 Filter: ((w = 1) OR (w = 2))
+                                 Rows Removed by Filter: 998
+               ->  Index Only Scan using starjoin_plan_p1_pkey on starjoin_plan_p1 p1 (never executed)
+                     Index Cond: (id = pf.d1)
+                     Heap Fetches: 0
+                     Index Searches: 0
+         ->  Index Only Scan using starjoin_plan_p2_pkey on starjoin_plan_p2 p2 (never executed)
+               Index Cond: (id = pf.d2)
+               Heap Fetches: 0
+               Index Searches: 0
+(22 rows)
+
+-- same query, GUC off
+SET enable_starjoin_ordering = off;
+SELECT pg_temp.starjoin_explain($$
+SELECT count(*) FROM starjoin_plan_pf AS pf
+  JOIN starjoin_plan_p1 AS p1 ON pf.d1 = p1.id
+  JOIN starjoin_plan_p2 AS p2 ON pf.d2 = p2.id
+  JOIN starjoin_plan_p3 AS p3 ON pf.d3 = p3.id
+ WHERE (p3.w = 1 AND pf.x = 1) OR (p3.w = 2 AND pf.x = 2)
+$$) AS "QUERY PLAN";
+                                                     QUERY PLAN                                                      
+---------------------------------------------------------------------------------------------------------------------
+ Aggregate (actual rows=1.00 loops=1)
+   ->  Nested Loop (actual rows=0.00 loops=1)
+         ->  Nested Loop (actual rows=0.00 loops=1)
+               ->  Nested Loop (actual rows=0.00 loops=1)
+                     Join Filter: ((p3.id = pf.d3) AND (((p3.w = 1) AND (pf.x = 1)) OR ((p3.w = 2) AND (pf.x = 2))))
+                     Rows Removed by Join Filter: 80
+                     ->  Seq Scan on starjoin_plan_pf pf (actual rows=40.00 loops=1)
+                           Filter: ((x = 1) OR (x = 2))
+                           Rows Removed by Filter: 19960
+                     ->  Materialize (actual rows=2.00 loops=40)
+                           Storage: Memory  Maximum Storage: NkB
+                           ->  Seq Scan on starjoin_plan_p3 p3 (actual rows=2.00 loops=1)
+                                 Filter: ((w = 1) OR (w = 2))
+                                 Rows Removed by Filter: 998
+               ->  Index Only Scan using starjoin_plan_p1_pkey on starjoin_plan_p1 p1 (never executed)
+                     Index Cond: (id = pf.d1)
+                     Heap Fetches: 0
+                     Index Searches: 0
+         ->  Index Only Scan using starjoin_plan_p2_pkey on starjoin_plan_p2 p2 (never executed)
+               Index Cond: (id = pf.d2)
+               Heap Fetches: 0
+               Index Searches: 0
+(22 rows)
+
+DROP TABLE starjoin_plan_pf, starjoin_plan_p1, starjoin_plan_p2, starjoin_plan_p3;
diff --git a/src/test/regress/expected/starjoin_plan_large.out b/src/test/regress/expected/starjoin_plan_large.out
new file mode 100644
index 00000000000..e8baa065a49
--- /dev/null
+++ b/src/test/regress/expected/starjoin_plan_large.out
@@ -0,0 +1,172 @@
+--
+-- STARJOIN_PLAN_LARGE
+-- Same as starjoin_plan, but with larger tables (expensive)
+--
+-- Ignore platform-dependent memory and hash sizing, but retain the
+-- distinction between single-batch and multi-batch hashing.
+CREATE OR REPLACE FUNCTION pg_temp.starjoin_explain(query text) RETURNS SETOF text
+LANGUAGE plpgsql AS $$
+DECLARE
+  ln text;
+BEGIN
+  FOR ln IN EXECUTE
+    'EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, BUFFERS OFF, SUMMARY OFF) ' || query
+  LOOP
+    ln := regexp_replace(ln, '\m\d+kB', 'NkB', 'g');
+    ln := regexp_replace(ln, 'Buckets: \d+', 'Buckets: N');
+    ln := regexp_replace(ln, 'Batches: (?!1\M)\d+', 'Batches: multiple');
+    ln := regexp_replace(ln, ' \(originally \d+\)', '', 'g');
+    RETURN NEXT ln;
+  END LOOP;
+END;
+$$;
+CREATE TABLE starjoin_plan_p1 (id int PRIMARY KEY, v int, w int);
+CREATE TABLE starjoin_plan_p2 (id int PRIMARY KEY, v int, w int);
+CREATE TABLE starjoin_plan_p3 (id int PRIMARY KEY, v int, w int);
+INSERT INTO starjoin_plan_p1 SELECT i, i % 100, i FROM generate_series(1,10000) i;
+INSERT INTO starjoin_plan_p2 SELECT i, i % 100, i FROM generate_series(1,10000) i;
+INSERT INTO starjoin_plan_p3 SELECT i, i % 100, i FROM generate_series(1,10000) i;
+CREATE TABLE starjoin_plan_pf (id int PRIMARY KEY,
+  d1 int NOT NULL REFERENCES starjoin_plan_p1,
+  d2 int NOT NULL REFERENCES starjoin_plan_p2,
+  d3 int NOT NULL REFERENCES starjoin_plan_p3,
+  x int);
+INSERT INTO starjoin_plan_pf SELECT i, 1 + (i * 7) % 10000, 1 + (i * 13) % 10000, 1 + (i * 17) % 10000, i % 1000
+  FROM generate_series(1,200000) i;
+VACUUM ANALYZE starjoin_plan_p1, starjoin_plan_p2, starjoin_plan_p3, starjoin_plan_pf;
+SET max_parallel_workers_per_gather = 0;
+-- Q1: extra (non-FK) join qual between fact and the last dimension. It makes
+-- the join to p3 selective, but p3 is still a dimension, so with the GUC on
+-- p3 is joined last, while with the GUC off it's joined first.
+-- join the fact to p1, p2 and p3, with an extra join qual for p3, GUC on
+SET enable_starjoin_ordering = on;
+SELECT pg_temp.starjoin_explain($$
+SELECT count(*) FROM starjoin_plan_pf AS pf
+  JOIN starjoin_plan_p1 AS p1 ON pf.d1 = p1.id
+  JOIN starjoin_plan_p2 AS p2 ON pf.d2 = p2.id
+  JOIN starjoin_plan_p3 AS p3 ON pf.d3 = p3.id AND pf.x = p3.w
+$$) AS "QUERY PLAN";
+                                          QUERY PLAN                                          
+----------------------------------------------------------------------------------------------
+ Aggregate (actual rows=1.00 loops=1)
+   ->  Hash Join (actual rows=0.00 loops=1)
+         Hash Cond: ((pf.d3 = p3.id) AND (pf.x = p3.w))
+         ->  Hash Join (actual rows=200000.00 loops=1)
+               Hash Cond: (pf.d2 = p2.id)
+               ->  Hash Join (actual rows=200000.00 loops=1)
+                     Hash Cond: (pf.d1 = p1.id)
+                     ->  Seq Scan on starjoin_plan_pf pf (actual rows=200000.00 loops=1)
+                     ->  Hash (actual rows=10000.00 loops=1)
+                           Buckets: N  Batches: 1  Memory Usage: NkB
+                           ->  Seq Scan on starjoin_plan_p1 p1 (actual rows=10000.00 loops=1)
+               ->  Hash (actual rows=10000.00 loops=1)
+                     Buckets: N  Batches: 1  Memory Usage: NkB
+                     ->  Seq Scan on starjoin_plan_p2 p2 (actual rows=10000.00 loops=1)
+         ->  Hash (actual rows=10000.00 loops=1)
+               Buckets: N  Batches: 1  Memory Usage: NkB
+               ->  Seq Scan on starjoin_plan_p3 p3 (actual rows=10000.00 loops=1)
+(17 rows)
+
+-- same query, GUC off
+SET enable_starjoin_ordering = off;
+SELECT pg_temp.starjoin_explain($$
+SELECT count(*) FROM starjoin_plan_pf AS pf
+  JOIN starjoin_plan_p1 AS p1 ON pf.d1 = p1.id
+  JOIN starjoin_plan_p2 AS p2 ON pf.d2 = p2.id
+  JOIN starjoin_plan_p3 AS p3 ON pf.d3 = p3.id AND pf.x = p3.w
+$$) AS "QUERY PLAN";
+                                              QUERY PLAN                                               
+-------------------------------------------------------------------------------------------------------
+ Aggregate (actual rows=1.00 loops=1)
+   ->  Nested Loop (actual rows=0.00 loops=1)
+         ->  Nested Loop (actual rows=0.00 loops=1)
+               ->  Hash Join (actual rows=0.00 loops=1)
+                     Hash Cond: ((pf.d3 = p3.id) AND (pf.x = p3.w))
+                     ->  Seq Scan on starjoin_plan_pf pf (actual rows=200000.00 loops=1)
+                     ->  Hash (actual rows=10000.00 loops=1)
+                           Buckets: N  Batches: 1  Memory Usage: NkB
+                           ->  Seq Scan on starjoin_plan_p3 p3 (actual rows=10000.00 loops=1)
+               ->  Index Only Scan using starjoin_plan_p1_pkey on starjoin_plan_p1 p1 (never executed)
+                     Index Cond: (id = pf.d1)
+                     Heap Fetches: 0
+                     Index Searches: 0
+         ->  Index Only Scan using starjoin_plan_p2_pkey on starjoin_plan_p2 p2 (never executed)
+               Index Cond: (id = pf.d2)
+               Heap Fetches: 0
+               Index Searches: 0
+(17 rows)
+
+-- Q2: OR clause from which extract_restriction_or_clauses() derives a
+-- restriction on p3, so p3 is not a dimension (the clusters are built after
+-- deriving the restrictions), and the plan is the same as with the GUC off.
+-- join the fact to p1, p2 and p3, with an OR clause in WHERE, GUC on
+SET enable_starjoin_ordering = on;
+SELECT pg_temp.starjoin_explain($$
+SELECT count(*) FROM starjoin_plan_pf AS pf
+  JOIN starjoin_plan_p1 AS p1 ON pf.d1 = p1.id
+  JOIN starjoin_plan_p2 AS p2 ON pf.d2 = p2.id
+  JOIN starjoin_plan_p3 AS p3 ON pf.d3 = p3.id
+ WHERE (p3.w = 1 AND pf.x = 1) OR (p3.w = 2 AND pf.x = 2)
+$$) AS "QUERY PLAN";
+                                                     QUERY PLAN                                                      
+---------------------------------------------------------------------------------------------------------------------
+ Aggregate (actual rows=1.00 loops=1)
+   ->  Nested Loop (actual rows=0.00 loops=1)
+         ->  Nested Loop (actual rows=0.00 loops=1)
+               ->  Nested Loop (actual rows=0.00 loops=1)
+                     Join Filter: ((p3.id = pf.d3) AND (((p3.w = 1) AND (pf.x = 1)) OR ((p3.w = 2) AND (pf.x = 2))))
+                     Rows Removed by Join Filter: 800
+                     ->  Seq Scan on starjoin_plan_pf pf (actual rows=400.00 loops=1)
+                           Filter: ((x = 1) OR (x = 2))
+                           Rows Removed by Filter: 199600
+                     ->  Materialize (actual rows=2.00 loops=400)
+                           Storage: Memory  Maximum Storage: NkB
+                           ->  Seq Scan on starjoin_plan_p3 p3 (actual rows=2.00 loops=1)
+                                 Filter: ((w = 1) OR (w = 2))
+                                 Rows Removed by Filter: 9998
+               ->  Index Only Scan using starjoin_plan_p1_pkey on starjoin_plan_p1 p1 (never executed)
+                     Index Cond: (id = pf.d1)
+                     Heap Fetches: 0
+                     Index Searches: 0
+         ->  Index Only Scan using starjoin_plan_p2_pkey on starjoin_plan_p2 p2 (never executed)
+               Index Cond: (id = pf.d2)
+               Heap Fetches: 0
+               Index Searches: 0
+(22 rows)
+
+-- same query, GUC off
+SET enable_starjoin_ordering = off;
+SELECT pg_temp.starjoin_explain($$
+SELECT count(*) FROM starjoin_plan_pf AS pf
+  JOIN starjoin_plan_p1 AS p1 ON pf.d1 = p1.id
+  JOIN starjoin_plan_p2 AS p2 ON pf.d2 = p2.id
+  JOIN starjoin_plan_p3 AS p3 ON pf.d3 = p3.id
+ WHERE (p3.w = 1 AND pf.x = 1) OR (p3.w = 2 AND pf.x = 2)
+$$) AS "QUERY PLAN";
+                                                     QUERY PLAN                                                      
+---------------------------------------------------------------------------------------------------------------------
+ Aggregate (actual rows=1.00 loops=1)
+   ->  Nested Loop (actual rows=0.00 loops=1)
+         ->  Nested Loop (actual rows=0.00 loops=1)
+               ->  Nested Loop (actual rows=0.00 loops=1)
+                     Join Filter: ((p3.id = pf.d3) AND (((p3.w = 1) AND (pf.x = 1)) OR ((p3.w = 2) AND (pf.x = 2))))
+                     Rows Removed by Join Filter: 800
+                     ->  Seq Scan on starjoin_plan_pf pf (actual rows=400.00 loops=1)
+                           Filter: ((x = 1) OR (x = 2))
+                           Rows Removed by Filter: 199600
+                     ->  Materialize (actual rows=2.00 loops=400)
+                           Storage: Memory  Maximum Storage: NkB
+                           ->  Seq Scan on starjoin_plan_p3 p3 (actual rows=2.00 loops=1)
+                                 Filter: ((w = 1) OR (w = 2))
+                                 Rows Removed by Filter: 9998
+               ->  Index Only Scan using starjoin_plan_p1_pkey on starjoin_plan_p1 p1 (never executed)
+                     Index Cond: (id = pf.d1)
+                     Heap Fetches: 0
+                     Index Searches: 0
+         ->  Index Only Scan using starjoin_plan_p2_pkey on starjoin_plan_p2 p2 (never executed)
+               Index Cond: (id = pf.d2)
+               Heap Fetches: 0
+               Index Searches: 0
+(22 rows)
+
+DROP TABLE starjoin_plan_pf, starjoin_plan_p1, starjoin_plan_p2, starjoin_plan_p3;
diff --git a/src/test/regress/expected/starjoin_planning.out b/src/test/regress/expected/starjoin_planning.out
new file mode 100644
index 00000000000..45c32b9b9c8
--- /dev/null
+++ b/src/test/regress/expected/starjoin_planning.out
@@ -0,0 +1,437 @@
+--
+-- STARJOIN_PLANNING
+-- Test star join ordering with the join search split into sub-problems
+--
+CREATE TABLE starjoin_planning_d0 (id int PRIMARY KEY, v int);
+CREATE TABLE starjoin_planning_d1 (id int PRIMARY KEY, v int);
+CREATE TABLE starjoin_planning_d2 (id int PRIMARY KEY, v int);
+CREATE TABLE starjoin_planning_d3 (id int PRIMARY KEY, v int);
+CREATE TABLE starjoin_planning_d4 (id int PRIMARY KEY, v int);
+CREATE TABLE starjoin_planning_d5 (id int PRIMARY KEY, v int);
+CREATE TABLE starjoin_planning_d6 (id int PRIMARY KEY, v int);
+CREATE TABLE starjoin_planning_d7 (id int PRIMARY KEY, v int);
+CREATE TABLE starjoin_planning_f (id int PRIMARY KEY,
+  d0 int NOT NULL REFERENCES starjoin_planning_d0,
+  d1 int NOT NULL REFERENCES starjoin_planning_d1,
+  d2 int NOT NULL REFERENCES starjoin_planning_d2,
+  d3 int NOT NULL REFERENCES starjoin_planning_d3,
+  d4 int NOT NULL REFERENCES starjoin_planning_d4,
+  d5 int NOT NULL REFERENCES starjoin_planning_d5,
+  d6 int NOT NULL REFERENCES starjoin_planning_d6,
+  d7 int NOT NULL REFERENCES starjoin_planning_d7,
+  x int);
+-- Tests A-H check that planning does not fail with "failed to build any N-way
+-- joins" when the canonical order can't be followed in a sub-problem, because
+-- some cluster members are not in the sub-problem, or were already joined in
+-- a lower sub-problem.
+-- A: explicit join order, sub-problem has fact + non-prefix dims, because d1
+-- (the first dimension in the canonical order) is joined only in the upper
+-- sub-problem
+SET join_collapse_limit = 1;
+-- join the fact to d2 and d3, and then the result to d1
+EXPLAIN (COSTS OFF) SELECT * FROM starjoin_planning_d1 AS d1 JOIN (starjoin_planning_f AS f JOIN starjoin_planning_d2 AS d2 ON f.d2 = d2.id JOIN starjoin_planning_d3 AS d3 ON f.d3 = d3.id) ON f.d1 = d1.id;
+                         QUERY PLAN                          
+-------------------------------------------------------------
+ Hash Join
+   Hash Cond: (f.d1 = d1.id)
+   ->  Hash Join
+         Hash Cond: (f.d3 = d3.id)
+         ->  Hash Join
+               Hash Cond: (f.d2 = d2.id)
+               ->  Seq Scan on starjoin_planning_f f
+               ->  Hash
+                     ->  Seq Scan on starjoin_planning_d2 d2
+         ->  Hash
+               ->  Seq Scan on starjoin_planning_d3 d3
+   ->  Hash
+         ->  Seq Scan on starjoin_planning_d1 d1
+(13 rows)
+
+-- B: explicit join order, sub-problem has dims but no fact, so the dims can
+-- be joined only by a cartesian product
+-- join the fact to the cartesian product of d1 and d2, GUC on
+SET enable_starjoin_ordering = on;
+EXPLAIN (COSTS OFF) SELECT * FROM starjoin_planning_f AS f JOIN (starjoin_planning_d1 AS d1 CROSS JOIN starjoin_planning_d2 AS d2) ON f.d1 = d1.id AND f.d2 = d2.id;
+                                    QUERY PLAN                                     
+-----------------------------------------------------------------------------------
+ Merge Join
+   Merge Cond: (d1.id = f.d1)
+   Join Filter: (d2.id = f.d2)
+   ->  Nested Loop
+         ->  Index Scan using starjoin_planning_d1_pkey on starjoin_planning_d1 d1
+         ->  Materialize
+               ->  Seq Scan on starjoin_planning_d2 d2
+   ->  Sort
+         Sort Key: f.d1
+         ->  Seq Scan on starjoin_planning_f f
+(10 rows)
+
+-- same query, GUC off
+SET enable_starjoin_ordering = off;
+EXPLAIN (COSTS OFF) SELECT * FROM starjoin_planning_f AS f JOIN (starjoin_planning_d1 AS d1 CROSS JOIN starjoin_planning_d2 AS d2) ON f.d1 = d1.id AND f.d2 = d2.id;
+                                    QUERY PLAN                                     
+-----------------------------------------------------------------------------------
+ Merge Join
+   Merge Cond: (d1.id = f.d1)
+   Join Filter: (d2.id = f.d2)
+   ->  Nested Loop
+         ->  Index Scan using starjoin_planning_d1_pkey on starjoin_planning_d1 d1
+         ->  Materialize
+               ->  Seq Scan on starjoin_planning_d2 d2
+   ->  Sort
+         Sort Key: f.d1
+         ->  Seq Scan on starjoin_planning_f f
+(10 rows)
+
+RESET enable_starjoin_ordering;
+RESET join_collapse_limit;
+-- C: default settings, 9 rels, join_collapse_limit (8) splits the problem,
+-- and d0 (the first dimension) is joined only in the upper sub-problem
+-- join the fact to d1-d7, and then the result to d0
+EXPLAIN (COSTS OFF) SELECT count(*) FROM starjoin_planning_d0 AS d0 JOIN (starjoin_planning_f AS f
+  JOIN starjoin_planning_d1 AS d1 ON f.d1 = d1.id
+  JOIN starjoin_planning_d2 AS d2 ON f.d2 = d2.id
+  JOIN starjoin_planning_d3 AS d3 ON f.d3 = d3.id
+  JOIN starjoin_planning_d4 AS d4 ON f.d4 = d4.id
+  JOIN starjoin_planning_d5 AS d5 ON f.d5 = d5.id
+  JOIN starjoin_planning_d6 AS d6 ON f.d6 = d6.id
+  JOIN starjoin_planning_d7 AS d7 ON f.d7 = d7.id) ON f.d0 = d0.id;
+                                           QUERY PLAN                                            
+-------------------------------------------------------------------------------------------------
+ Aggregate
+   ->  Hash Join
+         Hash Cond: (f.d0 = d0.id)
+         ->  Hash Join
+               Hash Cond: (f.d7 = d7.id)
+               ->  Hash Join
+                     Hash Cond: (f.d6 = d6.id)
+                     ->  Hash Join
+                           Hash Cond: (f.d5 = d5.id)
+                           ->  Hash Join
+                                 Hash Cond: (f.d4 = d4.id)
+                                 ->  Hash Join
+                                       Hash Cond: (f.d3 = d3.id)
+                                       ->  Hash Join
+                                             Hash Cond: (f.d2 = d2.id)
+                                             ->  Hash Join
+                                                   Hash Cond: (f.d1 = d1.id)
+                                                   ->  Seq Scan on starjoin_planning_f f
+                                                   ->  Hash
+                                                         ->  Seq Scan on starjoin_planning_d1 d1
+                                             ->  Hash
+                                                   ->  Seq Scan on starjoin_planning_d2 d2
+                                       ->  Hash
+                                             ->  Seq Scan on starjoin_planning_d3 d3
+                                 ->  Hash
+                                       ->  Seq Scan on starjoin_planning_d4 d4
+                           ->  Hash
+                                 ->  Seq Scan on starjoin_planning_d5 d5
+                     ->  Hash
+                           ->  Seq Scan on starjoin_planning_d6 d6
+               ->  Hash
+                     ->  Seq Scan on starjoin_planning_d7 d7
+         ->  Hash
+               ->  Seq Scan on starjoin_planning_d0 d0
+(34 rows)
+
+-- D: default settings, view + outer dimension, split the same way as in C
+CREATE VIEW starjoin_planning_star AS
+SELECT f.*, d1.v AS v1, d2.v AS v2, d3.v AS v3, d4.v AS v4, d5.v AS v5, d6.v AS v6, d7.v AS v7
+  FROM starjoin_planning_f AS f JOIN starjoin_planning_d1 AS d1 ON f.d1 = d1.id
+                                JOIN starjoin_planning_d2 AS d2 ON f.d2 = d2.id
+                                JOIN starjoin_planning_d3 AS d3 ON f.d3 = d3.id
+                                JOIN starjoin_planning_d4 AS d4 ON f.d4 = d4.id
+                                JOIN starjoin_planning_d5 AS d5 ON f.d5 = d5.id
+                                JOIN starjoin_planning_d6 AS d6 ON f.d6 = d6.id
+                                JOIN starjoin_planning_d7 AS d7 ON f.d7 = d7.id;
+-- join the view (the fact joined to d1-d7) to d0, GUC on
+EXPLAIN (COSTS OFF) SELECT count(*) FROM starjoin_planning_d0 AS d0 JOIN starjoin_planning_star s ON s.d0 = d0.id;
+                                           QUERY PLAN                                            
+-------------------------------------------------------------------------------------------------
+ Aggregate
+   ->  Hash Join
+         Hash Cond: (f.d0 = d0.id)
+         ->  Hash Join
+               Hash Cond: (f.d7 = d7.id)
+               ->  Hash Join
+                     Hash Cond: (f.d6 = d6.id)
+                     ->  Hash Join
+                           Hash Cond: (f.d5 = d5.id)
+                           ->  Hash Join
+                                 Hash Cond: (f.d4 = d4.id)
+                                 ->  Hash Join
+                                       Hash Cond: (f.d3 = d3.id)
+                                       ->  Hash Join
+                                             Hash Cond: (f.d2 = d2.id)
+                                             ->  Hash Join
+                                                   Hash Cond: (f.d1 = d1.id)
+                                                   ->  Seq Scan on starjoin_planning_f f
+                                                   ->  Hash
+                                                         ->  Seq Scan on starjoin_planning_d1 d1
+                                             ->  Hash
+                                                   ->  Seq Scan on starjoin_planning_d2 d2
+                                       ->  Hash
+                                             ->  Seq Scan on starjoin_planning_d3 d3
+                                 ->  Hash
+                                       ->  Seq Scan on starjoin_planning_d4 d4
+                           ->  Hash
+                                 ->  Seq Scan on starjoin_planning_d5 d5
+                     ->  Hash
+                           ->  Seq Scan on starjoin_planning_d6 d6
+               ->  Hash
+                     ->  Seq Scan on starjoin_planning_d7 d7
+         ->  Hash
+               ->  Seq Scan on starjoin_planning_d0 d0
+(34 rows)
+
+-- same query, GUC off
+SET enable_starjoin_ordering = off;
+EXPLAIN (COSTS OFF) SELECT count(*) FROM starjoin_planning_d0 AS d0 JOIN starjoin_planning_star s ON s.d0 = d0.id;
+                                           QUERY PLAN                                            
+-------------------------------------------------------------------------------------------------
+ Aggregate
+   ->  Hash Join
+         Hash Cond: (f.d0 = d0.id)
+         ->  Hash Join
+               Hash Cond: (f.d7 = d7.id)
+               ->  Hash Join
+                     Hash Cond: (f.d6 = d6.id)
+                     ->  Hash Join
+                           Hash Cond: (f.d5 = d5.id)
+                           ->  Hash Join
+                                 Hash Cond: (f.d4 = d4.id)
+                                 ->  Hash Join
+                                       Hash Cond: (f.d3 = d3.id)
+                                       ->  Hash Join
+                                             Hash Cond: (f.d2 = d2.id)
+                                             ->  Hash Join
+                                                   Hash Cond: (f.d1 = d1.id)
+                                                   ->  Seq Scan on starjoin_planning_f f
+                                                   ->  Hash
+                                                         ->  Seq Scan on starjoin_planning_d1 d1
+                                             ->  Hash
+                                                   ->  Seq Scan on starjoin_planning_d2 d2
+                                       ->  Hash
+                                             ->  Seq Scan on starjoin_planning_d3 d3
+                                 ->  Hash
+                                       ->  Seq Scan on starjoin_planning_d4 d4
+                           ->  Hash
+                                 ->  Seq Scan on starjoin_planning_d5 d5
+                     ->  Hash
+                           ->  Seq Scan on starjoin_planning_d6 d6
+               ->  Hash
+                     ->  Seq Scan on starjoin_planning_d7 d7
+         ->  Hash
+               ->  Seq Scan on starjoin_planning_d0 d0
+(34 rows)
+
+RESET enable_starjoin_ordering;
+-- E: default settings, comma FROM list with a pulled-up subquery, which
+-- from_collapse_limit keeps as a separate sub-problem with dims but no fact
+-- comma FROM list joining the fact to d0-d5, and to a subquery with the
+-- cartesian product of d6 and d7
+EXPLAIN (COSTS OFF) SELECT count(*) FROM starjoin_planning_f AS f, starjoin_planning_d0 AS d0,
+  starjoin_planning_d1 AS d1, starjoin_planning_d2 AS d2, starjoin_planning_d3 AS d3,
+  starjoin_planning_d4 AS d4, starjoin_planning_d5 AS d5,
+  (SELECT d6.id AS i6, d7.id AS i7 FROM starjoin_planning_d6 AS d6, starjoin_planning_d7 AS d7) s
+ WHERE f.d0 = d0.id AND f.d1 = d1.id AND f.d2 = d2.id AND f.d3 = d3.id
+   AND f.d4 = d4.id AND f.d5 = d5.id AND f.d6 = s.i6 AND f.d7 = s.i7;
+                                                            QUERY PLAN                                                            
+----------------------------------------------------------------------------------------------------------------------------------
+ Aggregate
+   ->  Nested Loop
+         ->  Nested Loop
+               ->  Nested Loop
+                     ->  Nested Loop
+                           ->  Nested Loop
+                                 ->  Nested Loop
+                                       ->  Merge Join
+                                             Merge Cond: (d6.id = f.d6)
+                                             Join Filter: (d7.id = f.d7)
+                                             ->  Nested Loop
+                                                   ->  Index Only Scan using starjoin_planning_d6_pkey on starjoin_planning_d6 d6
+                                                   ->  Materialize
+                                                         ->  Seq Scan on starjoin_planning_d7 d7
+                                             ->  Sort
+                                                   Sort Key: f.d6
+                                                   ->  Seq Scan on starjoin_planning_f f
+                                       ->  Index Only Scan using starjoin_planning_d0_pkey on starjoin_planning_d0 d0
+                                             Index Cond: (id = f.d0)
+                                 ->  Index Only Scan using starjoin_planning_d1_pkey on starjoin_planning_d1 d1
+                                       Index Cond: (id = f.d1)
+                           ->  Index Only Scan using starjoin_planning_d2_pkey on starjoin_planning_d2 d2
+                                 Index Cond: (id = f.d2)
+                     ->  Index Only Scan using starjoin_planning_d3_pkey on starjoin_planning_d3 d3
+                           Index Cond: (id = f.d3)
+               ->  Index Only Scan using starjoin_planning_d4_pkey on starjoin_planning_d4 d4
+                     Index Cond: (id = f.d4)
+         ->  Index Only Scan using starjoin_planning_d5_pkey on starjoin_planning_d5 d5
+               Index Cond: (id = f.d5)
+(29 rows)
+
+-- F: from_collapse_limit, the fact is joined to a dimension (with a higher
+-- relid than the other dimensions) in a separate subproblem, i.e. before the
+-- other dimensions, contrary to the canonical order
+SET from_collapse_limit = 3;
+-- comma FROM list with d1, d2 and the fact joined to d3
+EXPLAIN (COSTS OFF) SELECT count(*) FROM starjoin_planning_d1 AS d1, starjoin_planning_d2 AS d2,
+  starjoin_planning_f AS f JOIN starjoin_planning_d3 AS d3 ON f.d3 = d3.id
+ WHERE f.d1 = d1.id AND f.d2 = d2.id;
+                            QUERY PLAN                             
+-------------------------------------------------------------------
+ Aggregate
+   ->  Hash Join
+         Hash Cond: (f.d2 = d2.id)
+         ->  Hash Join
+               Hash Cond: (f.d1 = d1.id)
+               ->  Hash Join
+                     Hash Cond: (f.d3 = d3.id)
+                     ->  Seq Scan on starjoin_planning_f f
+                     ->  Hash
+                           ->  Seq Scan on starjoin_planning_d3 d3
+               ->  Hash
+                     ->  Seq Scan on starjoin_planning_d1 d1
+         ->  Hash
+               ->  Seq Scan on starjoin_planning_d2 d2
+(14 rows)
+
+RESET from_collapse_limit;
+-- G: same, but with default settings (9 rels exceed from_collapse_limit)
+-- comma FROM list with d0-d6 and the fact joined to d7
+EXPLAIN (COSTS OFF) SELECT count(*) FROM starjoin_planning_d0 AS d0,
+  starjoin_planning_d1 AS d1, starjoin_planning_d2 AS d2, starjoin_planning_d3 AS d3,
+  starjoin_planning_d4 AS d4, starjoin_planning_d5 AS d5, starjoin_planning_d6 AS d6,
+  starjoin_planning_f AS f JOIN starjoin_planning_d7 AS d7 ON f.d7 = d7.id
+ WHERE f.d0 = d0.id AND f.d1 = d1.id AND f.d2 = d2.id AND f.d3 = d3.id
+   AND f.d4 = d4.id AND f.d5 = d5.id AND f.d6 = d6.id;
+                                           QUERY PLAN                                            
+-------------------------------------------------------------------------------------------------
+ Aggregate
+   ->  Hash Join
+         Hash Cond: (f.d6 = d6.id)
+         ->  Hash Join
+               Hash Cond: (f.d5 = d5.id)
+               ->  Hash Join
+                     Hash Cond: (f.d4 = d4.id)
+                     ->  Hash Join
+                           Hash Cond: (f.d3 = d3.id)
+                           ->  Hash Join
+                                 Hash Cond: (f.d2 = d2.id)
+                                 ->  Hash Join
+                                       Hash Cond: (f.d1 = d1.id)
+                                       ->  Hash Join
+                                             Hash Cond: (f.d0 = d0.id)
+                                             ->  Hash Join
+                                                   Hash Cond: (f.d7 = d7.id)
+                                                   ->  Seq Scan on starjoin_planning_f f
+                                                   ->  Hash
+                                                         ->  Seq Scan on starjoin_planning_d7 d7
+                                             ->  Hash
+                                                   ->  Seq Scan on starjoin_planning_d0 d0
+                                       ->  Hash
+                                             ->  Seq Scan on starjoin_planning_d1 d1
+                                 ->  Hash
+                                       ->  Seq Scan on starjoin_planning_d2 d2
+                           ->  Hash
+                                 ->  Seq Scan on starjoin_planning_d3 d3
+                     ->  Hash
+                           ->  Seq Scan on starjoin_planning_d4 d4
+               ->  Hash
+                     ->  Seq Scan on starjoin_planning_d5 d5
+         ->  Hash
+               ->  Seq Scan on starjoin_planning_d6 d6
+(34 rows)
+
+-- H: join_collapse_limit, right-nested explicit joins, so the fact is joined
+-- to d3 and d4 in a separate sub-problem, before d1 and d2, contrary to the
+-- canonical order
+SET join_collapse_limit = 3;
+-- join the fact to d3 and d4, then the result to d2, and then to d1
+EXPLAIN (COSTS OFF) SELECT count(*) FROM starjoin_planning_d1 AS d1
+  JOIN (starjoin_planning_d2 AS d2
+        JOIN (starjoin_planning_f AS f
+              JOIN starjoin_planning_d3 AS d3 ON f.d3 = d3.id
+              JOIN starjoin_planning_d4 AS d4 ON f.d4 = d4.id)
+        ON f.d2 = d2.id)
+  ON f.d1 = d1.id;
+                               QUERY PLAN                                
+-------------------------------------------------------------------------
+ Aggregate
+   ->  Hash Join
+         Hash Cond: (f.d2 = d2.id)
+         ->  Hash Join
+               Hash Cond: (f.d1 = d1.id)
+               ->  Hash Join
+                     Hash Cond: (f.d4 = d4.id)
+                     ->  Hash Join
+                           Hash Cond: (f.d3 = d3.id)
+                           ->  Seq Scan on starjoin_planning_f f
+                           ->  Hash
+                                 ->  Seq Scan on starjoin_planning_d3 d3
+                     ->  Hash
+                           ->  Seq Scan on starjoin_planning_d4 d4
+               ->  Hash
+                     ->  Seq Scan on starjoin_planning_d1 d1
+         ->  Hash
+               ->  Seq Scan on starjoin_planning_d2 d2
+(18 rows)
+
+RESET join_collapse_limit;
+-- I: explicit join order, sub-problem has dimensions but no fact, so the
+-- canonical order is not enforced and the cartesian products may start with
+-- the small dimensions (d2, d3), just like with the GUC off
+INSERT INTO starjoin_planning_d1 SELECT i, i FROM generate_series(1, 1000) i;
+INSERT INTO starjoin_planning_d2 VALUES (1, 1), (2, 2);
+INSERT INTO starjoin_planning_d3 VALUES (1, 1), (2, 2);
+ANALYZE starjoin_planning_d1, starjoin_planning_d2, starjoin_planning_d3;
+SET join_collapse_limit = 3;
+-- join the fact to the cartesian product of d1, d2 and d3, GUC on
+SET enable_starjoin_ordering = on;
+EXPLAIN (COSTS OFF) SELECT count(*) FROM starjoin_planning_f AS f
+  JOIN (starjoin_planning_d1 AS d1 CROSS JOIN starjoin_planning_d2 AS d2
+        CROSS JOIN starjoin_planning_d3 AS d3)
+  ON f.d1 = d1.id AND f.d2 = d2.id AND f.d3 = d3.id;
+                                  QUERY PLAN                                   
+-------------------------------------------------------------------------------
+ Aggregate
+   ->  Hash Join
+         Hash Cond: ((f.d1 = d1.id) AND (f.d2 = d2.id) AND (f.d3 = d3.id))
+         ->  Seq Scan on starjoin_planning_f f
+         ->  Hash
+               ->  Nested Loop
+                     ->  Seq Scan on starjoin_planning_d1 d1
+                     ->  Materialize
+                           ->  Nested Loop
+                                 ->  Seq Scan on starjoin_planning_d2 d2
+                                 ->  Materialize
+                                       ->  Seq Scan on starjoin_planning_d3 d3
+(12 rows)
+
+-- same query, GUC off
+SET enable_starjoin_ordering = off;
+EXPLAIN (COSTS OFF) SELECT count(*) FROM starjoin_planning_f AS f
+  JOIN (starjoin_planning_d1 AS d1 CROSS JOIN starjoin_planning_d2 AS d2
+        CROSS JOIN starjoin_planning_d3 AS d3)
+  ON f.d1 = d1.id AND f.d2 = d2.id AND f.d3 = d3.id;
+                                  QUERY PLAN                                   
+-------------------------------------------------------------------------------
+ Aggregate
+   ->  Hash Join
+         Hash Cond: ((f.d1 = d1.id) AND (f.d2 = d2.id) AND (f.d3 = d3.id))
+         ->  Seq Scan on starjoin_planning_f f
+         ->  Hash
+               ->  Nested Loop
+                     ->  Seq Scan on starjoin_planning_d1 d1
+                     ->  Materialize
+                           ->  Nested Loop
+                                 ->  Seq Scan on starjoin_planning_d2 d2
+                                 ->  Materialize
+                                       ->  Seq Scan on starjoin_planning_d3 d3
+(12 rows)
+
+RESET enable_starjoin_ordering;
+RESET join_collapse_limit;
+DROP VIEW starjoin_planning_star;
+DROP TABLE starjoin_planning_f, starjoin_planning_d0, starjoin_planning_d1,
+  starjoin_planning_d2, starjoin_planning_d3, starjoin_planning_d4,
+  starjoin_planning_d5, starjoin_planning_d6, starjoin_planning_d7;
diff --git a/src/test/regress/expected/starjoin_reproducers.out b/src/test/regress/expected/starjoin_reproducers.out
new file mode 100644
index 00000000000..9fd7a429649
--- /dev/null
+++ b/src/test/regress/expected/starjoin_reproducers.out
@@ -0,0 +1,656 @@
+--
+-- Planning queries with enable_starjoin_ordering, where the join search
+-- can't simply follow the canonical order
+--
+-- In queries A-I, the clusters (determined for the whole query) and the join
+-- search subproblems (sub-joinlists, determined by
+-- join_collapse_limit/from_collapse_limit, explicit joins, views and
+-- subqueries) do not align, so the canonical order can't be followed in some
+-- subproblem.  The canonical-order check must not reject all joins the
+-- subproblem can build, otherwise the planning fails with "ERROR:  failed to
+-- build any N-way joins".
+--
+-- In query J, the last-ditch pass joins dimensions to rels without the fact,
+-- and two such rels then get joined.
+--
+-- For each query, show the plan with the GUC enabled, and then check that
+-- the query returns the same result with the GUC enabled and disabled.
+--
+CREATE TABLE starjoin_reproducers_d0 (id int PRIMARY KEY, v int) WITH (autovacuum_enabled = off);
+CREATE TABLE starjoin_reproducers_d1 (id int PRIMARY KEY, v int) WITH (autovacuum_enabled = off);
+CREATE TABLE starjoin_reproducers_d2 (id int PRIMARY KEY, v int) WITH (autovacuum_enabled = off);
+CREATE TABLE starjoin_reproducers_d3 (id int PRIMARY KEY, v int) WITH (autovacuum_enabled = off);
+CREATE TABLE starjoin_reproducers_d4 (id int PRIMARY KEY, v int) WITH (autovacuum_enabled = off);
+CREATE TABLE starjoin_reproducers_d5 (id int PRIMARY KEY, v int) WITH (autovacuum_enabled = off);
+CREATE TABLE starjoin_reproducers_d6 (id int PRIMARY KEY, v int) WITH (autovacuum_enabled = off);
+CREATE TABLE starjoin_reproducers_d7 (id int PRIMARY KEY, v int) WITH (autovacuum_enabled = off);
+CREATE TABLE starjoin_reproducers_f (id int PRIMARY KEY,
+  d0 int NOT NULL REFERENCES starjoin_reproducers_d0,
+  d1 int NOT NULL REFERENCES starjoin_reproducers_d1,
+  d2 int NOT NULL REFERENCES starjoin_reproducers_d2,
+  d3 int NOT NULL REFERENCES starjoin_reproducers_d3,
+  d4 int NOT NULL REFERENCES starjoin_reproducers_d4,
+  d5 int NOT NULL REFERENCES starjoin_reproducers_d5,
+  d6 int NOT NULL REFERENCES starjoin_reproducers_d6,
+  d7 int NOT NULL REFERENCES starjoin_reproducers_d7,
+  x int) WITH (autovacuum_enabled = off);
+INSERT INTO starjoin_reproducers_d0 SELECT i, i FROM generate_series(1, 10) i;
+INSERT INTO starjoin_reproducers_d1 SELECT i, 10 * i FROM generate_series(1, 20) i;
+INSERT INTO starjoin_reproducers_d2 SELECT i, 100 * i FROM generate_series(1, 30) i;
+INSERT INTO starjoin_reproducers_d3 SELECT i, 1000 * i FROM generate_series(1, 40) i;
+INSERT INTO starjoin_reproducers_d4 SELECT i, i FROM generate_series(1, 50) i;
+INSERT INTO starjoin_reproducers_d5 SELECT i, 10 * i FROM generate_series(1, 60) i;
+INSERT INTO starjoin_reproducers_d6 SELECT i, 100 * i FROM generate_series(1, 70) i;
+INSERT INTO starjoin_reproducers_d7 SELECT i, 1000 * i FROM generate_series(1, 80) i;
+INSERT INTO starjoin_reproducers_f
+SELECT i, 1 + i % 10, 1 + (i * 3) % 20, 1 + (i * 7) % 30, 1 + (i * 11) % 40,
+       1 + (i * 13) % 50, 1 + (i * 17) % 60, 1 + (i * 19) % 70, 1 + (i * 23) % 80, i
+  FROM generate_series(1, 500) i;
+-- small table for the outer joins (used by J)
+CREATE TABLE starjoin_reproducers_t (a int, b int) WITH (autovacuum_enabled = off);
+INSERT INTO starjoin_reproducers_t SELECT i % 2, i % 3 FROM generate_series(1, 4) i;
+VACUUM ANALYZE starjoin_reproducers_d0, starjoin_reproducers_d1,
+  starjoin_reproducers_d2, starjoin_reproducers_d3, starjoin_reproducers_d4,
+  starjoin_reproducers_d5, starjoin_reproducers_d6, starjoin_reproducers_d7,
+  starjoin_reproducers_f, starjoin_reproducers_t;
+-- star over the fact and dimensions d1-d7 (used by D)
+CREATE VIEW starjoin_reproducers_star AS
+SELECT f.*, d1.v AS v1, d2.v AS v2, d3.v AS v3, d4.v AS v4, d5.v AS v5,
+       d6.v AS v6, d7.v AS v7
+  FROM starjoin_reproducers_f AS f
+  JOIN starjoin_reproducers_d1 AS d1 ON f.d1 = d1.id
+  JOIN starjoin_reproducers_d2 AS d2 ON f.d2 = d2.id
+  JOIN starjoin_reproducers_d3 AS d3 ON f.d3 = d3.id
+  JOIN starjoin_reproducers_d4 AS d4 ON f.d4 = d4.id
+  JOIN starjoin_reproducers_d5 AS d5 ON f.d5 = d5.id
+  JOIN starjoin_reproducers_d6 AS d6 ON f.d6 = d6.id
+  JOIN starjoin_reproducers_d7 AS d7 ON f.d7 = d7.id;
+-- fact joined to a single dimension d7 (used by H)
+CREATE VIEW starjoin_reproducers_fv AS
+SELECT f.*, d7.v AS v7
+  FROM starjoin_reproducers_f AS f
+  JOIN starjoin_reproducers_d7 AS d7 ON f.d7 = d7.id;
+-- run the query with the GUC enabled and disabled, return both results
+CREATE FUNCTION starjoin_reproducers_check(query text,
+                                           OUT starjoin_on text,
+                                           OUT starjoin_off text)
+LANGUAGE plpgsql AS $$
+BEGIN
+  PERFORM set_config('enable_starjoin_ordering', 'on', true);
+  EXECUTE format('SELECT row(q.*)::text FROM (%s) q', query) INTO starjoin_on;
+  PERFORM set_config('enable_starjoin_ordering', 'off', true);
+  EXECUTE format('SELECT row(q.*)::text FROM (%s) q', query) INTO starjoin_off;
+END;
+$$;
+SET enable_starjoin_ordering = on;
+-- A: explicit join order, the subproblem has the fact and dimensions that are
+-- not a prefix of the canonical order (d1 is joined in the upper subproblem)
+SET join_collapse_limit = 1;
+EXPLAIN (COSTS OFF)
+SELECT count(*), sum(d1.v + d2.v + d3.v)
+  FROM starjoin_reproducers_d1 AS d1
+  JOIN (starjoin_reproducers_f AS f
+        JOIN starjoin_reproducers_d2 AS d2 ON f.d2 = d2.id
+        JOIN starjoin_reproducers_d3 AS d3 ON f.d3 = d3.id) ON f.d1 = d1.id;
+                              QUERY PLAN                              
+----------------------------------------------------------------------
+ Aggregate
+   ->  Hash Join
+         Hash Cond: (f.d1 = d1.id)
+         ->  Hash Join
+               Hash Cond: (f.d3 = d3.id)
+               ->  Hash Join
+                     Hash Cond: (f.d2 = d2.id)
+                     ->  Seq Scan on starjoin_reproducers_f f
+                     ->  Hash
+                           ->  Seq Scan on starjoin_reproducers_d2 d2
+               ->  Hash
+                     ->  Seq Scan on starjoin_reproducers_d3 d3
+         ->  Hash
+               ->  Seq Scan on starjoin_reproducers_d1 d1
+(14 rows)
+
+SELECT * FROM starjoin_reproducers_check($$
+SELECT count(*), sum(d1.v + d2.v + d3.v)
+  FROM starjoin_reproducers_d1 AS d1
+  JOIN (starjoin_reproducers_f AS f
+        JOIN starjoin_reproducers_d2 AS d2 ON f.d2 = d2.id
+        JOIN starjoin_reproducers_d3 AS d3 ON f.d3 = d3.id) ON f.d1 = d1.id
+$$);
+  starjoin_on   |  starjoin_off  
+----------------+----------------
+ (500,11078500) | (500,11078500)
+(1 row)
+
+-- B: explicit join order, the subproblem has dimensions but not the fact
+EXPLAIN (COSTS OFF)
+SELECT count(*), sum(d1.v + d2.v)
+  FROM starjoin_reproducers_f AS f
+  JOIN (starjoin_reproducers_d1 AS d1 CROSS JOIN starjoin_reproducers_d2 AS d2)
+    ON f.d1 = d1.id AND f.d2 = d2.id;
+                           QUERY PLAN                           
+----------------------------------------------------------------
+ Aggregate
+   ->  Hash Join
+         Hash Cond: ((d1.id = f.d1) AND (d2.id = f.d2))
+         ->  Nested Loop
+               ->  Seq Scan on starjoin_reproducers_d2 d2
+               ->  Materialize
+                     ->  Seq Scan on starjoin_reproducers_d1 d1
+         ->  Hash
+               ->  Seq Scan on starjoin_reproducers_f f
+(9 rows)
+
+SELECT * FROM starjoin_reproducers_check($$
+SELECT count(*), sum(d1.v + d2.v)
+  FROM starjoin_reproducers_f AS f
+  JOIN (starjoin_reproducers_d1 AS d1 CROSS JOIN starjoin_reproducers_d2 AS d2)
+    ON f.d1 = d1.id AND f.d2 = d2.id
+$$);
+ starjoin_on  | starjoin_off 
+--------------+--------------
+ (500,828500) | (500,828500)
+(1 row)
+
+RESET join_collapse_limit;
+-- C: default settings, 9 rels, join_collapse_limit splits the problem, and
+-- the first dimension (d0) is joined in the upper subproblem
+EXPLAIN (COSTS OFF)
+SELECT count(*), sum(d0.v + d7.v)
+  FROM starjoin_reproducers_d0 AS d0
+  JOIN (starjoin_reproducers_f AS f
+        JOIN starjoin_reproducers_d1 AS d1 ON f.d1 = d1.id
+        JOIN starjoin_reproducers_d2 AS d2 ON f.d2 = d2.id
+        JOIN starjoin_reproducers_d3 AS d3 ON f.d3 = d3.id
+        JOIN starjoin_reproducers_d4 AS d4 ON f.d4 = d4.id
+        JOIN starjoin_reproducers_d5 AS d5 ON f.d5 = d5.id
+        JOIN starjoin_reproducers_d6 AS d6 ON f.d6 = d6.id
+        JOIN starjoin_reproducers_d7 AS d7 ON f.d7 = d7.id) ON f.d0 = d0.id;
+                                             QUERY PLAN                                             
+----------------------------------------------------------------------------------------------------
+ Aggregate
+   ->  Hash Join
+         Hash Cond: (f.d0 = d0.id)
+         ->  Hash Join
+               Hash Cond: (f.d7 = d7.id)
+               ->  Hash Join
+                     Hash Cond: (f.d6 = d6.id)
+                     ->  Hash Join
+                           Hash Cond: (f.d5 = d5.id)
+                           ->  Hash Join
+                                 Hash Cond: (f.d4 = d4.id)
+                                 ->  Hash Join
+                                       Hash Cond: (f.d3 = d3.id)
+                                       ->  Hash Join
+                                             Hash Cond: (f.d2 = d2.id)
+                                             ->  Hash Join
+                                                   Hash Cond: (f.d1 = d1.id)
+                                                   ->  Seq Scan on starjoin_reproducers_f f
+                                                   ->  Hash
+                                                         ->  Seq Scan on starjoin_reproducers_d1 d1
+                                             ->  Hash
+                                                   ->  Seq Scan on starjoin_reproducers_d2 d2
+                                       ->  Hash
+                                             ->  Seq Scan on starjoin_reproducers_d3 d3
+                                 ->  Hash
+                                       ->  Seq Scan on starjoin_reproducers_d4 d4
+                           ->  Hash
+                                 ->  Seq Scan on starjoin_reproducers_d5 d5
+                     ->  Hash
+                           ->  Seq Scan on starjoin_reproducers_d6 d6
+               ->  Hash
+                     ->  Seq Scan on starjoin_reproducers_d7 d7
+         ->  Hash
+               ->  Seq Scan on starjoin_reproducers_d0 d0
+(34 rows)
+
+SELECT * FROM starjoin_reproducers_check($$
+SELECT count(*), sum(d0.v + d7.v)
+  FROM starjoin_reproducers_d0 AS d0
+  JOIN (starjoin_reproducers_f AS f
+        JOIN starjoin_reproducers_d1 AS d1 ON f.d1 = d1.id
+        JOIN starjoin_reproducers_d2 AS d2 ON f.d2 = d2.id
+        JOIN starjoin_reproducers_d3 AS d3 ON f.d3 = d3.id
+        JOIN starjoin_reproducers_d4 AS d4 ON f.d4 = d4.id
+        JOIN starjoin_reproducers_d5 AS d5 ON f.d5 = d5.id
+        JOIN starjoin_reproducers_d6 AS d6 ON f.d6 = d6.id
+        JOIN starjoin_reproducers_d7 AS d7 ON f.d7 = d7.id) ON f.d0 = d0.id
+$$);
+  starjoin_on   |  starjoin_off  
+----------------+----------------
+ (500,20212750) | (500,20212750)
+(1 row)
+
+-- D: default settings, view over the star, joined to another dimension
+EXPLAIN (COSTS OFF)
+SELECT count(*), sum(d0.v + s.v1 + s.v7)
+  FROM starjoin_reproducers_d0 AS d0
+  JOIN starjoin_reproducers_star AS s ON s.d0 = d0.id;
+                                             QUERY PLAN                                             
+----------------------------------------------------------------------------------------------------
+ Aggregate
+   ->  Hash Join
+         Hash Cond: (f.d0 = d0.id)
+         ->  Hash Join
+               Hash Cond: (f.d7 = d7.id)
+               ->  Hash Join
+                     Hash Cond: (f.d6 = d6.id)
+                     ->  Hash Join
+                           Hash Cond: (f.d5 = d5.id)
+                           ->  Hash Join
+                                 Hash Cond: (f.d4 = d4.id)
+                                 ->  Hash Join
+                                       Hash Cond: (f.d3 = d3.id)
+                                       ->  Hash Join
+                                             Hash Cond: (f.d2 = d2.id)
+                                             ->  Hash Join
+                                                   Hash Cond: (f.d1 = d1.id)
+                                                   ->  Seq Scan on starjoin_reproducers_f f
+                                                   ->  Hash
+                                                         ->  Seq Scan on starjoin_reproducers_d1 d1
+                                             ->  Hash
+                                                   ->  Seq Scan on starjoin_reproducers_d2 d2
+                                       ->  Hash
+                                             ->  Seq Scan on starjoin_reproducers_d3 d3
+                                 ->  Hash
+                                       ->  Seq Scan on starjoin_reproducers_d4 d4
+                           ->  Hash
+                                 ->  Seq Scan on starjoin_reproducers_d5 d5
+                     ->  Hash
+                           ->  Seq Scan on starjoin_reproducers_d6 d6
+               ->  Hash
+                     ->  Seq Scan on starjoin_reproducers_d7 d7
+         ->  Hash
+               ->  Seq Scan on starjoin_reproducers_d0 d0
+(34 rows)
+
+SELECT * FROM starjoin_reproducers_check($$
+SELECT count(*), sum(d0.v + s.v1 + s.v7)
+  FROM starjoin_reproducers_d0 AS d0
+  JOIN starjoin_reproducers_star AS s ON s.d0 = d0.id
+$$);
+  starjoin_on   |  starjoin_off  
+----------------+----------------
+ (500,20265250) | (500,20265250)
+(1 row)
+
+-- E: default settings, FROM list with a pulled-up subquery, split by
+-- from_collapse_limit
+EXPLAIN (COSTS OFF)
+SELECT count(*), sum(d0.v + s.v6 + s.v7)
+  FROM starjoin_reproducers_f AS f,
+       starjoin_reproducers_d0 AS d0, starjoin_reproducers_d1 AS d1,
+       starjoin_reproducers_d2 AS d2, starjoin_reproducers_d3 AS d3,
+       starjoin_reproducers_d4 AS d4, starjoin_reproducers_d5 AS d5,
+       (SELECT d6.id AS i6, d6.v AS v6, d7.id AS i7, d7.v AS v7
+          FROM starjoin_reproducers_d6 AS d6,
+               starjoin_reproducers_d7 AS d7) AS s
+ WHERE f.d0 = d0.id AND f.d1 = d1.id AND f.d2 = d2.id AND f.d3 = d3.id
+   AND f.d4 = d4.id AND f.d5 = d5.id AND f.d6 = s.i6 AND f.d7 = s.i7;
+                                             QUERY PLAN                                             
+----------------------------------------------------------------------------------------------------
+ Aggregate
+   ->  Hash Join
+         Hash Cond: (f.d5 = d5.id)
+         ->  Hash Join
+               Hash Cond: (f.d4 = d4.id)
+               ->  Hash Join
+                     Hash Cond: (f.d3 = d3.id)
+                     ->  Hash Join
+                           Hash Cond: (f.d2 = d2.id)
+                           ->  Hash Join
+                                 Hash Cond: (f.d1 = d1.id)
+                                 ->  Hash Join
+                                       Hash Cond: (f.d0 = d0.id)
+                                       ->  Hash Join
+                                             Hash Cond: ((d6.id = f.d6) AND (d7.id = f.d7))
+                                             ->  Nested Loop
+                                                   ->  Seq Scan on starjoin_reproducers_d7 d7
+                                                   ->  Materialize
+                                                         ->  Seq Scan on starjoin_reproducers_d6 d6
+                                             ->  Hash
+                                                   ->  Seq Scan on starjoin_reproducers_f f
+                                       ->  Hash
+                                             ->  Seq Scan on starjoin_reproducers_d0 d0
+                                 ->  Hash
+                                       ->  Seq Scan on starjoin_reproducers_d1 d1
+                           ->  Hash
+                                 ->  Seq Scan on starjoin_reproducers_d2 d2
+                     ->  Hash
+                           ->  Seq Scan on starjoin_reproducers_d3 d3
+               ->  Hash
+                     ->  Seq Scan on starjoin_reproducers_d4 d4
+         ->  Hash
+               ->  Seq Scan on starjoin_reproducers_d5 d5
+(33 rows)
+
+SELECT * FROM starjoin_reproducers_check($$
+SELECT count(*), sum(d0.v + s.v6 + s.v7)
+  FROM starjoin_reproducers_f AS f,
+       starjoin_reproducers_d0 AS d0, starjoin_reproducers_d1 AS d1,
+       starjoin_reproducers_d2 AS d2, starjoin_reproducers_d3 AS d3,
+       starjoin_reproducers_d4 AS d4, starjoin_reproducers_d5 AS d5,
+       (SELECT d6.id AS i6, d6.v AS v6, d7.id AS i7, d7.v AS v7
+          FROM starjoin_reproducers_d6 AS d6,
+               starjoin_reproducers_d7 AS d7) AS s
+ WHERE f.d0 = d0.id AND f.d1 = d1.id AND f.d2 = d2.id AND f.d3 = d3.id
+   AND f.d4 = d4.id AND f.d5 = d5.id AND f.d6 = s.i6 AND f.d7 = s.i7
+$$);
+  starjoin_on   |  starjoin_off  
+----------------+----------------
+ (500,21987750) | (500,21987750)
+(1 row)
+
+-- F: from_collapse_limit = 3, FROM list with an explicit join of the fact
+-- and a dimension with higher relid than the dimensions in the FROM list
+SET from_collapse_limit = 3;
+EXPLAIN (COSTS OFF)
+SELECT count(*), sum(d1.v + d2.v + d3.v)
+  FROM starjoin_reproducers_d1 AS d1, starjoin_reproducers_d2 AS d2,
+       starjoin_reproducers_f AS f
+       JOIN starjoin_reproducers_d3 AS d3 ON f.d3 = d3.id
+ WHERE f.d1 = d1.id AND f.d2 = d2.id;
+                              QUERY PLAN                              
+----------------------------------------------------------------------
+ Aggregate
+   ->  Hash Join
+         Hash Cond: (f.d2 = d2.id)
+         ->  Hash Join
+               Hash Cond: (f.d1 = d1.id)
+               ->  Hash Join
+                     Hash Cond: (f.d3 = d3.id)
+                     ->  Seq Scan on starjoin_reproducers_f f
+                     ->  Hash
+                           ->  Seq Scan on starjoin_reproducers_d3 d3
+               ->  Hash
+                     ->  Seq Scan on starjoin_reproducers_d1 d1
+         ->  Hash
+               ->  Seq Scan on starjoin_reproducers_d2 d2
+(14 rows)
+
+SELECT * FROM starjoin_reproducers_check($$
+SELECT count(*), sum(d1.v + d2.v + d3.v)
+  FROM starjoin_reproducers_d1 AS d1, starjoin_reproducers_d2 AS d2,
+       starjoin_reproducers_f AS f
+       JOIN starjoin_reproducers_d3 AS d3 ON f.d3 = d3.id
+ WHERE f.d1 = d1.id AND f.d2 = d2.id
+$$);
+  starjoin_on   |  starjoin_off  
+----------------+----------------
+ (500,11078500) | (500,11078500)
+(1 row)
+
+RESET from_collapse_limit;
+-- G: default settings, 7 dimensions in the FROM list, and an explicit join
+-- of the fact and the last dimension (9 rels > from_collapse_limit)
+EXPLAIN (COSTS OFF)
+SELECT count(*), sum(d0.v + d6.v + d7.v)
+  FROM starjoin_reproducers_d0 AS d0, starjoin_reproducers_d1 AS d1,
+       starjoin_reproducers_d2 AS d2, starjoin_reproducers_d3 AS d3,
+       starjoin_reproducers_d4 AS d4, starjoin_reproducers_d5 AS d5,
+       starjoin_reproducers_d6 AS d6,
+       starjoin_reproducers_f AS f
+       JOIN starjoin_reproducers_d7 AS d7 ON f.d7 = d7.id
+ WHERE f.d0 = d0.id AND f.d1 = d1.id AND f.d2 = d2.id AND f.d3 = d3.id
+   AND f.d4 = d4.id AND f.d5 = d5.id AND f.d6 = d6.id;
+                                             QUERY PLAN                                             
+----------------------------------------------------------------------------------------------------
+ Aggregate
+   ->  Hash Join
+         Hash Cond: (f.d6 = d6.id)
+         ->  Hash Join
+               Hash Cond: (f.d5 = d5.id)
+               ->  Hash Join
+                     Hash Cond: (f.d4 = d4.id)
+                     ->  Hash Join
+                           Hash Cond: (f.d3 = d3.id)
+                           ->  Hash Join
+                                 Hash Cond: (f.d2 = d2.id)
+                                 ->  Hash Join
+                                       Hash Cond: (f.d1 = d1.id)
+                                       ->  Hash Join
+                                             Hash Cond: (f.d0 = d0.id)
+                                             ->  Hash Join
+                                                   Hash Cond: (f.d7 = d7.id)
+                                                   ->  Seq Scan on starjoin_reproducers_f f
+                                                   ->  Hash
+                                                         ->  Seq Scan on starjoin_reproducers_d7 d7
+                                             ->  Hash
+                                                   ->  Seq Scan on starjoin_reproducers_d0 d0
+                                       ->  Hash
+                                             ->  Seq Scan on starjoin_reproducers_d1 d1
+                                 ->  Hash
+                                       ->  Seq Scan on starjoin_reproducers_d2 d2
+                           ->  Hash
+                                 ->  Seq Scan on starjoin_reproducers_d3 d3
+                     ->  Hash
+                           ->  Seq Scan on starjoin_reproducers_d4 d4
+               ->  Hash
+                     ->  Seq Scan on starjoin_reproducers_d5 d5
+         ->  Hash
+               ->  Seq Scan on starjoin_reproducers_d6 d6
+(34 rows)
+
+SELECT * FROM starjoin_reproducers_check($$
+SELECT count(*), sum(d0.v + d6.v + d7.v)
+  FROM starjoin_reproducers_d0 AS d0, starjoin_reproducers_d1 AS d1,
+       starjoin_reproducers_d2 AS d2, starjoin_reproducers_d3 AS d3,
+       starjoin_reproducers_d4 AS d4, starjoin_reproducers_d5 AS d5,
+       starjoin_reproducers_d6 AS d6,
+       starjoin_reproducers_f AS f
+       JOIN starjoin_reproducers_d7 AS d7 ON f.d7 = d7.id
+ WHERE f.d0 = d0.id AND f.d1 = d1.id AND f.d2 = d2.id AND f.d3 = d3.id
+   AND f.d4 = d4.id AND f.d5 = d5.id AND f.d6 = d6.id
+$$);
+  starjoin_on   |  starjoin_off  
+----------------+----------------
+ (500,21987750) | (500,21987750)
+(1 row)
+
+-- H: default settings, view over the fact and the last dimension, joined to
+-- the 7 other dimensions
+EXPLAIN (COSTS OFF)
+SELECT count(*), sum(d0.v + d6.v + fv.v7)
+  FROM starjoin_reproducers_d0 AS d0, starjoin_reproducers_d1 AS d1,
+       starjoin_reproducers_d2 AS d2, starjoin_reproducers_d3 AS d3,
+       starjoin_reproducers_d4 AS d4, starjoin_reproducers_d5 AS d5,
+       starjoin_reproducers_d6 AS d6, starjoin_reproducers_fv AS fv
+ WHERE fv.d0 = d0.id AND fv.d1 = d1.id AND fv.d2 = d2.id AND fv.d3 = d3.id
+   AND fv.d4 = d4.id AND fv.d5 = d5.id AND fv.d6 = d6.id;
+                                             QUERY PLAN                                             
+----------------------------------------------------------------------------------------------------
+ Aggregate
+   ->  Hash Join
+         Hash Cond: (f.d6 = d6.id)
+         ->  Hash Join
+               Hash Cond: (f.d5 = d5.id)
+               ->  Hash Join
+                     Hash Cond: (f.d4 = d4.id)
+                     ->  Hash Join
+                           Hash Cond: (f.d3 = d3.id)
+                           ->  Hash Join
+                                 Hash Cond: (f.d2 = d2.id)
+                                 ->  Hash Join
+                                       Hash Cond: (f.d1 = d1.id)
+                                       ->  Hash Join
+                                             Hash Cond: (f.d0 = d0.id)
+                                             ->  Hash Join
+                                                   Hash Cond: (f.d7 = d7.id)
+                                                   ->  Seq Scan on starjoin_reproducers_f f
+                                                   ->  Hash
+                                                         ->  Seq Scan on starjoin_reproducers_d7 d7
+                                             ->  Hash
+                                                   ->  Seq Scan on starjoin_reproducers_d0 d0
+                                       ->  Hash
+                                             ->  Seq Scan on starjoin_reproducers_d1 d1
+                                 ->  Hash
+                                       ->  Seq Scan on starjoin_reproducers_d2 d2
+                           ->  Hash
+                                 ->  Seq Scan on starjoin_reproducers_d3 d3
+                     ->  Hash
+                           ->  Seq Scan on starjoin_reproducers_d4 d4
+               ->  Hash
+                     ->  Seq Scan on starjoin_reproducers_d5 d5
+         ->  Hash
+               ->  Seq Scan on starjoin_reproducers_d6 d6
+(34 rows)
+
+SELECT * FROM starjoin_reproducers_check($$
+SELECT count(*), sum(d0.v + d6.v + fv.v7)
+  FROM starjoin_reproducers_d0 AS d0, starjoin_reproducers_d1 AS d1,
+       starjoin_reproducers_d2 AS d2, starjoin_reproducers_d3 AS d3,
+       starjoin_reproducers_d4 AS d4, starjoin_reproducers_d5 AS d5,
+       starjoin_reproducers_d6 AS d6, starjoin_reproducers_fv AS fv
+ WHERE fv.d0 = d0.id AND fv.d1 = d1.id AND fv.d2 = d2.id AND fv.d3 = d3.id
+   AND fv.d4 = d4.id AND fv.d5 = d5.id AND fv.d6 = d6.id
+$$);
+  starjoin_on   |  starjoin_off  
+----------------+----------------
+ (500,21987750) | (500,21987750)
+(1 row)
+
+-- I: join_collapse_limit = 3, right-nested explicit joins
+SET join_collapse_limit = 3;
+EXPLAIN (COSTS OFF)
+SELECT count(*), sum(d1.v + d2.v + d3.v + d4.v)
+  FROM starjoin_reproducers_d1 AS d1
+  JOIN (starjoin_reproducers_d2 AS d2
+        JOIN (starjoin_reproducers_f AS f
+              JOIN starjoin_reproducers_d3 AS d3 ON f.d3 = d3.id
+              JOIN starjoin_reproducers_d4 AS d4 ON f.d4 = d4.id)
+          ON f.d2 = d2.id)
+    ON f.d1 = d1.id;
+                                 QUERY PLAN                                 
+----------------------------------------------------------------------------
+ Aggregate
+   ->  Hash Join
+         Hash Cond: (f.d2 = d2.id)
+         ->  Hash Join
+               Hash Cond: (f.d1 = d1.id)
+               ->  Hash Join
+                     Hash Cond: (f.d4 = d4.id)
+                     ->  Hash Join
+                           Hash Cond: (f.d3 = d3.id)
+                           ->  Seq Scan on starjoin_reproducers_f f
+                           ->  Hash
+                                 ->  Seq Scan on starjoin_reproducers_d3 d3
+                     ->  Hash
+                           ->  Seq Scan on starjoin_reproducers_d4 d4
+               ->  Hash
+                     ->  Seq Scan on starjoin_reproducers_d1 d1
+         ->  Hash
+               ->  Seq Scan on starjoin_reproducers_d2 d2
+(18 rows)
+
+SELECT * FROM starjoin_reproducers_check($$
+SELECT count(*), sum(d1.v + d2.v + d3.v + d4.v)
+  FROM starjoin_reproducers_d1 AS d1
+  JOIN (starjoin_reproducers_d2 AS d2
+        JOIN (starjoin_reproducers_f AS f
+              JOIN starjoin_reproducers_d3 AS d3 ON f.d3 = d3.id
+              JOIN starjoin_reproducers_d4 AS d4 ON f.d4 = d4.id)
+          ON f.d2 = d2.id)
+    ON f.d1 = d1.id
+$$);
+  starjoin_on   |  starjoin_off  
+----------------+----------------
+ (500,11091250) | (500,11091250)
+(1 row)
+
+RESET join_collapse_limit;
+-- J: from_collapse_limit = 9, the subquery is a separate subproblem with the
+-- star (the fact has a join clause only to w, outside the subquery) and two
+-- outer joins of three rels each, linked by a non-strict clause between their
+-- nullable sides.  Nothing can be joined at level 4, so the last-ditch pass
+-- joins the outer joins to dimensions, and the clause then joins those rels.
+SET from_collapse_limit = 9;
+EXPLAIN (COSTS OFF)
+SELECT count(*)
+  FROM starjoin_reproducers_t AS w,
+       (SELECT f.x
+          FROM starjoin_reproducers_f AS f
+          JOIN starjoin_reproducers_d1 AS d1 ON f.d1 = d1.id
+          JOIN starjoin_reproducers_d2 AS d2 ON f.d2 = d2.id,
+               starjoin_reproducers_t AS p
+          LEFT JOIN (starjoin_reproducers_t AS q
+                     JOIN starjoin_reproducers_t AS q2 ON q.a = q2.a)
+            ON p.a = q.a,
+               starjoin_reproducers_t AS s
+          LEFT JOIN (starjoin_reproducers_t AS t
+                     JOIN starjoin_reproducers_t AS t2 ON t.a = t2.a)
+            ON s.a = t.a
+         WHERE f.id <= 10 AND coalesce(q.b, 0) = coalesce(t.b, 0)) AS sub
+ WHERE sub.x = w.a;
+                                                     QUERY PLAN                                                     
+--------------------------------------------------------------------------------------------------------------------
+ Aggregate
+   ->  Hash Join
+         Hash Cond: (f.x = w.a)
+         ->  Hash Join
+               Hash Cond: (COALESCE(t.b, 0) = COALESCE(q.b, 0))
+               ->  Hash Left Join
+                     Hash Cond: (s.a = t.a)
+                     ->  Nested Loop
+                           ->  Hash Join
+                                 Hash Cond: (f.d2 = d2.id)
+                                 ->  Hash Join
+                                       Hash Cond: (f.d1 = d1.id)
+                                       ->  Index Scan using starjoin_reproducers_f_pkey on starjoin_reproducers_f f
+                                             Index Cond: (id <= 10)
+                                       ->  Hash
+                                             ->  Seq Scan on starjoin_reproducers_d1 d1
+                                 ->  Hash
+                                       ->  Seq Scan on starjoin_reproducers_d2 d2
+                           ->  Materialize
+                                 ->  Seq Scan on starjoin_reproducers_t s
+                     ->  Hash
+                           ->  Hash Join
+                                 Hash Cond: (t.a = t2.a)
+                                 ->  Seq Scan on starjoin_reproducers_t t
+                                 ->  Hash
+                                       ->  Seq Scan on starjoin_reproducers_t t2
+               ->  Hash
+                     ->  Hash Right Join
+                           Hash Cond: (q.a = p.a)
+                           ->  Hash Join
+                                 Hash Cond: (q.a = q2.a)
+                                 ->  Seq Scan on starjoin_reproducers_t q
+                                 ->  Hash
+                                       ->  Seq Scan on starjoin_reproducers_t q2
+                           ->  Hash
+                                 ->  Seq Scan on starjoin_reproducers_t p
+         ->  Hash
+               ->  Seq Scan on starjoin_reproducers_t w
+(38 rows)
+
+SELECT * FROM starjoin_reproducers_check($$
+SELECT count(*)
+  FROM starjoin_reproducers_t AS w,
+       (SELECT f.x
+          FROM starjoin_reproducers_f AS f
+          JOIN starjoin_reproducers_d1 AS d1 ON f.d1 = d1.id
+          JOIN starjoin_reproducers_d2 AS d2 ON f.d2 = d2.id,
+               starjoin_reproducers_t AS p
+          LEFT JOIN (starjoin_reproducers_t AS q
+                     JOIN starjoin_reproducers_t AS q2 ON q.a = q2.a)
+            ON p.a = q.a,
+               starjoin_reproducers_t AS s
+          LEFT JOIN (starjoin_reproducers_t AS t
+                     JOIN starjoin_reproducers_t AS t2 ON t.a = t2.a)
+            ON s.a = t.a
+         WHERE f.id <= 10 AND coalesce(q.b, 0) = coalesce(t.b, 0)) AS sub
+ WHERE sub.x = w.a
+$$);
+ starjoin_on | starjoin_off 
+-------------+--------------
+ (192)       | (192)
+(1 row)
+
+RESET from_collapse_limit;
+RESET enable_starjoin_ordering;
+DROP FUNCTION starjoin_reproducers_check(text);
+DROP VIEW starjoin_reproducers_star, starjoin_reproducers_fv;
+DROP TABLE starjoin_reproducers_f, starjoin_reproducers_d0,
+  starjoin_reproducers_d1, starjoin_reproducers_d2, starjoin_reproducers_d3,
+  starjoin_reproducers_d4, starjoin_reproducers_d5, starjoin_reproducers_d6,
+  starjoin_reproducers_d7, starjoin_reproducers_t;
diff --git a/src/test/regress/expected/starjoin_width.out b/src/test/regress/expected/starjoin_width.out
new file mode 100644
index 00000000000..db9949add4f
--- /dev/null
+++ b/src/test/regress/expected/starjoin_width.out
@@ -0,0 +1,89 @@
+--
+-- STARJOIN_WIDTH
+-- Test star join ordering with dimensions of very different widths
+--
+-- Ignore platform-dependent memory and hash sizing, but retain the
+-- distinction between single-batch and multi-batch hashing.
+CREATE OR REPLACE FUNCTION pg_temp.starjoin_explain(query text) RETURNS SETOF text
+LANGUAGE plpgsql AS $$
+DECLARE
+  ln text;
+BEGIN
+  FOR ln IN EXECUTE
+    'EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, BUFFERS OFF, SUMMARY OFF) ' || query
+  LOOP
+    ln := regexp_replace(ln, '\m\d+kB', 'NkB', 'g');
+    ln := regexp_replace(ln, 'Buckets: \d+', 'Buckets: N');
+    ln := regexp_replace(ln, 'Batches: (?!1\M)\d+', 'Batches: multiple');
+    ln := regexp_replace(ln, ' \(originally \d+\)', '', 'g');
+    RETURN NEXT ln;
+  END LOOP;
+END;
+$$;
+CREATE TABLE starjoin_width_wa (id int PRIMARY KEY, t text);
+CREATE TABLE starjoin_width_wb (id int PRIMARY KEY, t text);
+CREATE TABLE starjoin_width_wc (id int PRIMARY KEY, v int);
+INSERT INTO starjoin_width_wa SELECT i, repeat(md5(i::text), 16) FROM generate_series(1,100) i;
+INSERT INTO starjoin_width_wb SELECT i, repeat(md5(i::text), 16) FROM generate_series(1,100) i;
+INSERT INTO starjoin_width_wc SELECT i, i FROM generate_series(1,10000) i;
+CREATE TABLE starjoin_width_wf (id int, a int NOT NULL REFERENCES starjoin_width_wa, b int NOT NULL REFERENCES starjoin_width_wb, c int NOT NULL REFERENCES starjoin_width_wc);
+INSERT INTO starjoin_width_wf SELECT i, 1 + i % 100, 1 + (i * 7) % 100, 1 + (i * 13) % 10000 FROM generate_series(1,10000) i;
+VACUUM ANALYZE starjoin_width_wa, starjoin_width_wb, starjoin_width_wc, starjoin_width_wf;
+SET max_parallel_workers_per_gather = 0;
+SET work_mem = '4MB';
+SET enable_nestloop = off; SET enable_mergejoin = off;
+-- All the joins preserve the cardinality, but the cost of a batched hash join
+-- depends on the width of the outer rows. So when the hash join to wc needs
+-- multiple batches (as in starjoin_width_large), the plan with the GUC off
+-- joins wc before the wide dimensions (wa, wb), while the canonical order
+-- joins it last. Otherwise the plans are the same.
+-- pure FK joins, GUC on
+SELECT pg_temp.starjoin_explain($$
+SELECT wa.t, wb.t, wc.v FROM starjoin_width_wf AS wf JOIN starjoin_width_wa AS wa ON wf.a = wa.id JOIN starjoin_width_wb AS wb ON wf.b = wb.id JOIN starjoin_width_wc AS wc ON wf.c = wc.id
+$$) AS "QUERY PLAN";
+                                      QUERY PLAN                                       
+---------------------------------------------------------------------------------------
+ Hash Join (actual rows=10000.00 loops=1)
+   Hash Cond: (wf.c = wc.id)
+   ->  Hash Join (actual rows=10000.00 loops=1)
+         Hash Cond: (wf.b = wb.id)
+         ->  Hash Join (actual rows=10000.00 loops=1)
+               Hash Cond: (wf.a = wa.id)
+               ->  Seq Scan on starjoin_width_wf wf (actual rows=10000.00 loops=1)
+               ->  Hash (actual rows=100.00 loops=1)
+                     Buckets: N  Batches: 1  Memory Usage: NkB
+                     ->  Seq Scan on starjoin_width_wa wa (actual rows=100.00 loops=1)
+         ->  Hash (actual rows=100.00 loops=1)
+               Buckets: N  Batches: 1  Memory Usage: NkB
+               ->  Seq Scan on starjoin_width_wb wb (actual rows=100.00 loops=1)
+   ->  Hash (actual rows=10000.00 loops=1)
+         Buckets: N  Batches: 1  Memory Usage: NkB
+         ->  Seq Scan on starjoin_width_wc wc (actual rows=10000.00 loops=1)
+(16 rows)
+
+-- pure FK joins, GUC off
+SET enable_starjoin_ordering = off;
+SELECT pg_temp.starjoin_explain($$
+SELECT wa.t, wb.t, wc.v FROM starjoin_width_wf AS wf JOIN starjoin_width_wa AS wa ON wf.a = wa.id JOIN starjoin_width_wb AS wb ON wf.b = wb.id JOIN starjoin_width_wc AS wc ON wf.c = wc.id
+$$) AS "QUERY PLAN";
+                                      QUERY PLAN                                       
+---------------------------------------------------------------------------------------
+ Hash Join (actual rows=10000.00 loops=1)
+   Hash Cond: (wf.c = wc.id)
+   ->  Hash Join (actual rows=10000.00 loops=1)
+         Hash Cond: (wf.b = wb.id)
+         ->  Hash Join (actual rows=10000.00 loops=1)
+               Hash Cond: (wf.a = wa.id)
+               ->  Seq Scan on starjoin_width_wf wf (actual rows=10000.00 loops=1)
+               ->  Hash (actual rows=100.00 loops=1)
+                     Buckets: N  Batches: 1  Memory Usage: NkB
+                     ->  Seq Scan on starjoin_width_wa wa (actual rows=100.00 loops=1)
+         ->  Hash (actual rows=100.00 loops=1)
+               Buckets: N  Batches: 1  Memory Usage: NkB
+               ->  Seq Scan on starjoin_width_wb wb (actual rows=100.00 loops=1)
+   ->  Hash (actual rows=10000.00 loops=1)
+         Buckets: N  Batches: 1  Memory Usage: NkB
+         ->  Seq Scan on starjoin_width_wc wc (actual rows=10000.00 loops=1)
+(16 rows)
+
+DROP TABLE starjoin_width_wf, starjoin_width_wa, starjoin_width_wb, starjoin_width_wc;
diff --git a/src/test/regress/expected/starjoin_width_large.out b/src/test/regress/expected/starjoin_width_large.out
new file mode 100644
index 00000000000..8c11fec1c2e
--- /dev/null
+++ b/src/test/regress/expected/starjoin_width_large.out
@@ -0,0 +1,90 @@
+--
+-- STARJOIN_WIDTH_LARGE
+-- Same as starjoin_width, but with larger tables (expensive)
+--
+-- Ignore platform-dependent memory and hash sizing, but retain the
+-- distinction between single-batch and multi-batch hashing.
+CREATE OR REPLACE FUNCTION pg_temp.starjoin_explain(query text) RETURNS SETOF text
+LANGUAGE plpgsql AS $$
+DECLARE
+  ln text;
+BEGIN
+  FOR ln IN EXECUTE
+    'EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, BUFFERS OFF, SUMMARY OFF) ' || query
+  LOOP
+    ln := regexp_replace(ln, '\m\d+kB', 'NkB', 'g');
+    ln := regexp_replace(ln, 'Buckets: \d+', 'Buckets: N');
+    ln := regexp_replace(ln, 'Batches: (?!1\M)\d+', 'Batches: multiple');
+    ln := regexp_replace(ln, ' \(originally \d+\)', '', 'g');
+    RETURN NEXT ln;
+  END LOOP;
+END;
+$$;
+CREATE TABLE starjoin_width_wa (id int PRIMARY KEY, t text);
+CREATE TABLE starjoin_width_wb (id int PRIMARY KEY, t text);
+CREATE TABLE starjoin_width_wc (id int PRIMARY KEY, v int);
+INSERT INTO starjoin_width_wa SELECT i, repeat(md5(i::text), 16) FROM generate_series(1,100) i;
+INSERT INTO starjoin_width_wb SELECT i, repeat(md5(i::text), 16) FROM generate_series(1,100) i;
+INSERT INTO starjoin_width_wc SELECT i, i FROM generate_series(1,100000) i;
+CREATE TABLE starjoin_width_wf (id int, a int NOT NULL REFERENCES starjoin_width_wa, b int NOT NULL REFERENCES starjoin_width_wb, c int NOT NULL REFERENCES starjoin_width_wc);
+INSERT INTO starjoin_width_wf SELECT i, 1 + i % 100, 1 + (i * 7) % 100, 1 + (i * 13) % 100000 FROM generate_series(1,100000) i;
+VACUUM ANALYZE starjoin_width_wa, starjoin_width_wb, starjoin_width_wc, starjoin_width_wf;
+SET max_parallel_workers_per_gather = 0;
+-- Use a small work_mem, so that the hash join to wc needs multiple batches.
+SET work_mem = '400kB';
+SET enable_nestloop = off; SET enable_mergejoin = off;
+-- All the joins preserve the cardinality, but the cost of a batched hash join
+-- depends on the width of the outer rows. So when the hash join to wc needs
+-- multiple batches (as in starjoin_width_large), the plan with the GUC off
+-- joins wc before the wide dimensions (wa, wb), while the canonical order
+-- joins it last. Otherwise the plans are the same.
+-- pure FK joins, GUC on
+SELECT pg_temp.starjoin_explain($$
+SELECT wa.t, wb.t, wc.v FROM starjoin_width_wf AS wf JOIN starjoin_width_wa AS wa ON wf.a = wa.id JOIN starjoin_width_wb AS wb ON wf.b = wb.id JOIN starjoin_width_wc AS wc ON wf.c = wc.id
+$$) AS "QUERY PLAN";
+                                      QUERY PLAN                                       
+---------------------------------------------------------------------------------------
+ Hash Join (actual rows=100000.00 loops=1)
+   Hash Cond: (wf.c = wc.id)
+   ->  Hash Join (actual rows=100000.00 loops=1)
+         Hash Cond: (wf.b = wb.id)
+         ->  Hash Join (actual rows=100000.00 loops=1)
+               Hash Cond: (wf.a = wa.id)
+               ->  Seq Scan on starjoin_width_wf wf (actual rows=100000.00 loops=1)
+               ->  Hash (actual rows=100.00 loops=1)
+                     Buckets: N  Batches: 1  Memory Usage: NkB
+                     ->  Seq Scan on starjoin_width_wa wa (actual rows=100.00 loops=1)
+         ->  Hash (actual rows=100.00 loops=1)
+               Buckets: N  Batches: 1  Memory Usage: NkB
+               ->  Seq Scan on starjoin_width_wb wb (actual rows=100.00 loops=1)
+   ->  Hash (actual rows=100000.00 loops=1)
+         Buckets: N  Batches: multiple  Memory Usage: NkB
+         ->  Seq Scan on starjoin_width_wc wc (actual rows=100000.00 loops=1)
+(16 rows)
+
+-- pure FK joins, GUC off
+SET enable_starjoin_ordering = off;
+SELECT pg_temp.starjoin_explain($$
+SELECT wa.t, wb.t, wc.v FROM starjoin_width_wf AS wf JOIN starjoin_width_wa AS wa ON wf.a = wa.id JOIN starjoin_width_wb AS wb ON wf.b = wb.id JOIN starjoin_width_wc AS wc ON wf.c = wc.id
+$$) AS "QUERY PLAN";
+                                        QUERY PLAN                                        
+------------------------------------------------------------------------------------------
+ Hash Join (actual rows=100000.00 loops=1)
+   Hash Cond: (wf.b = wb.id)
+   ->  Hash Join (actual rows=100000.00 loops=1)
+         Hash Cond: (wf.a = wa.id)
+         ->  Hash Join (actual rows=100000.00 loops=1)
+               Hash Cond: (wf.c = wc.id)
+               ->  Seq Scan on starjoin_width_wf wf (actual rows=100000.00 loops=1)
+               ->  Hash (actual rows=100000.00 loops=1)
+                     Buckets: N  Batches: multiple  Memory Usage: NkB
+                     ->  Seq Scan on starjoin_width_wc wc (actual rows=100000.00 loops=1)
+         ->  Hash (actual rows=100.00 loops=1)
+               Buckets: N  Batches: 1  Memory Usage: NkB
+               ->  Seq Scan on starjoin_width_wa wa (actual rows=100.00 loops=1)
+   ->  Hash (actual rows=100.00 loops=1)
+         Buckets: N  Batches: 1  Memory Usage: NkB
+         ->  Seq Scan on starjoin_width_wb wb (actual rows=100.00 loops=1)
+(16 rows)
+
+DROP TABLE starjoin_width_wf, starjoin_width_wa, starjoin_width_wb, starjoin_width_wc;
diff --git a/src/test/regress/expected/sysviews.out b/src/test/regress/expected/sysviews.out
index 1e327c2afa4..59541a6a504 100644
--- a/src/test/regress/expected/sysviews.out
+++ b/src/test/regress/expected/sysviews.out
@@ -180,8 +180,9 @@ select name, setting from pg_settings where name like 'enable%';
  enable_self_join_elimination   | on
  enable_seqscan                 | on
  enable_sort                    | on
+ enable_starjoin_ordering       | on
  enable_tidscan                 | on
-(26 rows)
+(27 rows)
 
 -- There are always wait event descriptions for various types.  InjectionPoint
 -- may be present or absent, depending on history since last postmaster start.
diff --git a/src/test/regress/parallel_schedule b/src/test/regress/parallel_schedule
index bb13a7b6b8f..70dfcd21d24 100644
--- a/src/test/regress/parallel_schedule
+++ b/src/test/regress/parallel_schedule
@@ -148,6 +148,12 @@ test: event_trigger_login
 # this test also uses event triggers, so likewise run it by itself
 test: fast_default
 
+# some tests for starjoin planning
+test: starjoin_planning starjoin_eager starjoin_plan starjoin_width starjoin_reproducers starjoin_other
+
+# more expensive tests for starjoin planning (larger variants of earlier tests)
+# test: starjoin_eager_large starjoin_plan_large starjoin_width_large
+
 # run tablespace test at the end because it drops the tablespace created during
 # setup that other tests may use.
 test: tablespace
diff --git a/src/test/regress/sql/join.sql b/src/test/regress/sql/join.sql
index 27b44016717..f2e1172111f 100644
--- a/src/test/regress/sql/join.sql
+++ b/src/test/regress/sql/join.sql
@@ -5076,3 +5076,39 @@ FROM (VALUES (1)) AS v(z) LEFT JOIN
 WHERE s.x = s.c;
 
 ROLLBACK;
+
+--
+-- Star-join collapse: FK-unique star clusters get a canonical join order
+--
+CREATE TABLE sj_d1 (id int PRIMARY KEY, v text);
+CREATE TABLE sj_d2 (id int PRIMARY KEY, v text);
+CREATE TABLE sj_d3 (id int PRIMARY KEY, v text);
+CREATE TABLE sj_f (
+    id int PRIMARY KEY,
+    d1 int NOT NULL REFERENCES sj_d1,
+    d2 int NOT NULL REFERENCES sj_d2,
+    d3 int NOT NULL REFERENCES sj_d3
+);
+ANALYZE sj_f, sj_d1, sj_d2, sj_d3;
+
+-- With the collapse enabled (default), the resulting plan must be identical
+-- to the plan produced with the optimization disabled.
+
+-- join the fact to all three dimensions, GUC on
+SET enable_starjoin_ordering = on;
+EXPLAIN (COSTS OFF)
+SELECT * FROM sj_f
+  JOIN sj_d1 ON sj_f.d1 = sj_d1.id
+  JOIN sj_d2 ON sj_f.d2 = sj_d2.id
+  JOIN sj_d3 ON sj_f.d3 = sj_d3.id;
+
+-- same query, GUC off
+SET enable_starjoin_ordering = off;
+EXPLAIN (COSTS OFF)
+SELECT * FROM sj_f
+  JOIN sj_d1 ON sj_f.d1 = sj_d1.id
+  JOIN sj_d2 ON sj_f.d2 = sj_d2.id
+  JOIN sj_d3 ON sj_f.d3 = sj_d3.id;
+
+RESET enable_starjoin_ordering;
+DROP TABLE sj_f, sj_d1, sj_d2, sj_d3;
diff --git a/src/test/regress/sql/starjoin_eager.sql b/src/test/regress/sql/starjoin_eager.sql
new file mode 100644
index 00000000000..71b2ff27043
--- /dev/null
+++ b/src/test/regress/sql/starjoin_eager.sql
@@ -0,0 +1,94 @@
+--
+-- STARJOIN_EAGER
+-- Test star join ordering combined with eager aggregation
+--
+
+-- Ignore platform-dependent memory and hash sizing, but retain the
+-- distinction between single-batch and multi-batch hashing.
+CREATE OR REPLACE FUNCTION pg_temp.starjoin_explain(query text) RETURNS SETOF text
+LANGUAGE plpgsql AS $$
+DECLARE
+  ln text;
+BEGIN
+  FOR ln IN EXECUTE
+    'EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, BUFFERS OFF, SUMMARY OFF) ' || query
+  LOOP
+    ln := regexp_replace(ln, '\m\d+kB', 'NkB', 'g');
+    ln := regexp_replace(ln, 'Buckets: \d+', 'Buckets: N');
+    ln := regexp_replace(ln, 'Batches: (?!1\M)\d+', 'Batches: multiple');
+    ln := regexp_replace(ln, ' \(originally \d+\)', '', 'g');
+    RETURN NEXT ln;
+  END LOOP;
+END;
+$$;
+
+CREATE TABLE starjoin_eager_h1 (id int PRIMARY KEY, v int);
+CREATE TABLE starjoin_eager_h2 (id int PRIMARY KEY, v int);
+CREATE TABLE starjoin_eager_h3 (id int PRIMARY KEY, v int);
+
+INSERT INTO starjoin_eager_h1 SELECT i, i % 10 FROM generate_series(1,100) i;
+INSERT INTO starjoin_eager_h2 SELECT i, i FROM generate_series(1,10000) i;
+INSERT INTO starjoin_eager_h3 SELECT i, i FROM generate_series(1,10000) i;
+
+CREATE TABLE starjoin_eager_hf (id int, d1 int NOT NULL, d2 int NOT NULL, d3 int NOT NULL, x int);
+INSERT INTO starjoin_eager_hf SELECT i, 1 + i % 100, 1 + (i * 7) % 10000, 1 + (i * 13) % 10000, i % 1000
+  FROM generate_series(1,20000) i;
+
+ALTER TABLE starjoin_eager_hf
+  ADD FOREIGN KEY (d1) REFERENCES starjoin_eager_h1,
+  ADD FOREIGN KEY (d2) REFERENCES starjoin_eager_h2,
+  ADD FOREIGN KEY (d3) REFERENCES starjoin_eager_h3;
+
+VACUUM ANALYZE starjoin_eager_h1, starjoin_eager_h2,
+               starjoin_eager_h3, starjoin_eager_hf;
+
+SET max_parallel_workers_per_gather = 0;
+
+-- With the GUC on, hf is never joined to h2 and h3 before h1, the first
+-- dimension in the canonical order, so the partial aggregation (grouping by
+-- hf.d1) can't be done below the join to h1, unlike with the GUC off.
+
+-- eager agg, GROUP BY first dim (h1), GUC on
+SET enable_starjoin_ordering = on;
+SELECT pg_temp.starjoin_explain($$
+SELECT h1.v, sum(hf.x)
+FROM starjoin_eager_hf AS hf JOIN starjoin_eager_h1 AS h1 ON hf.d1 = h1.id
+                             JOIN starjoin_eager_h2 AS h2 ON hf.d2 = h2.id
+                             JOIN starjoin_eager_h3 AS h3 ON hf.d3 = h3.id
+GROUP BY h1.v
+$$) AS "QUERY PLAN";
+
+-- eager agg, GROUP BY first dim (h1), GUC off
+SET enable_starjoin_ordering = off;
+SELECT pg_temp.starjoin_explain($$
+SELECT h1.v, sum(hf.x)
+FROM starjoin_eager_hf AS hf JOIN starjoin_eager_h1 AS h1 ON hf.d1 = h1.id
+                             JOIN starjoin_eager_h2 AS h2 ON hf.d2 = h2.id
+                             JOIN starjoin_eager_h3 AS h3 ON hf.d3 = h3.id
+GROUP BY h1.v
+$$) AS "QUERY PLAN";
+
+-- With h1 last in FROM, and so also last in the canonical order, the partial
+-- aggregation is done below the join to h1 with the GUC on too.
+
+-- same query, h1 written last in FROM, GUC on
+SET enable_starjoin_ordering = on;
+SELECT pg_temp.starjoin_explain($$
+SELECT h1.v, sum(hf.x)
+FROM starjoin_eager_hf AS hf JOIN starjoin_eager_h2 AS h2 ON hf.d2 = h2.id
+                             JOIN starjoin_eager_h3 AS h3 ON hf.d3 = h3.id
+                             JOIN starjoin_eager_h1 AS h1 ON hf.d1 = h1.id
+GROUP BY h1.v
+$$) AS "QUERY PLAN";
+
+-- same query, h1 written last in FROM, GUC off
+SET enable_starjoin_ordering = off;
+SELECT pg_temp.starjoin_explain($$
+SELECT h1.v, sum(hf.x)
+FROM starjoin_eager_hf AS hf JOIN starjoin_eager_h2 AS h2 ON hf.d2 = h2.id
+                             JOIN starjoin_eager_h3 AS h3 ON hf.d3 = h3.id
+                             JOIN starjoin_eager_h1 AS h1 ON hf.d1 = h1.id
+GROUP BY h1.v
+$$) AS "QUERY PLAN";
+
+DROP TABLE starjoin_eager_hf, starjoin_eager_h1, starjoin_eager_h2, starjoin_eager_h3;
diff --git a/src/test/regress/sql/starjoin_eager_large.sql b/src/test/regress/sql/starjoin_eager_large.sql
new file mode 100644
index 00000000000..cfd0ab282a7
--- /dev/null
+++ b/src/test/regress/sql/starjoin_eager_large.sql
@@ -0,0 +1,97 @@
+--
+-- STARJOIN_EAGER_LARGE
+-- Same as starjoin_eager, but with larger tables (expensive)
+--
+
+-- Ignore platform-dependent memory and hash sizing, but retain the
+-- distinction between single-batch and multi-batch hashing.
+CREATE OR REPLACE FUNCTION pg_temp.starjoin_explain(query text) RETURNS SETOF text
+LANGUAGE plpgsql AS $$
+DECLARE
+  ln text;
+BEGIN
+  FOR ln IN EXECUTE
+    'EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, BUFFERS OFF, SUMMARY OFF) ' || query
+  LOOP
+    ln := regexp_replace(ln, '\m\d+kB', 'NkB', 'g');
+    ln := regexp_replace(ln, 'Buckets: \d+', 'Buckets: N');
+    ln := regexp_replace(ln, 'Batches: (?!1\M)\d+', 'Batches: multiple');
+    ln := regexp_replace(ln, ' \(originally \d+\)', '', 'g');
+    RETURN NEXT ln;
+  END LOOP;
+END;
+$$;
+
+CREATE TABLE starjoin_eager_h1 (id int PRIMARY KEY, v int);
+CREATE TABLE starjoin_eager_h2 (id int PRIMARY KEY, v int);
+CREATE TABLE starjoin_eager_h3 (id int PRIMARY KEY, v int);
+
+INSERT INTO starjoin_eager_h1 SELECT i, i % 10 FROM generate_series(1,100) i;
+INSERT INTO starjoin_eager_h2 SELECT i, i FROM generate_series(1,100000) i;
+INSERT INTO starjoin_eager_h3 SELECT i, i FROM generate_series(1,100000) i;
+
+CREATE TABLE starjoin_eager_hf (id int, d1 int NOT NULL, d2 int NOT NULL, d3 int NOT NULL, x int);
+INSERT INTO starjoin_eager_hf SELECT i, 1 + i % 100, 1 + (i * 7) % 100000, 1 + (i * 13) % 100000, i % 1000
+  FROM generate_series(1,200000) i;
+
+ALTER TABLE starjoin_eager_hf
+  ADD FOREIGN KEY (d1) REFERENCES starjoin_eager_h1,
+  ADD FOREIGN KEY (d2) REFERENCES starjoin_eager_h2,
+  ADD FOREIGN KEY (d3) REFERENCES starjoin_eager_h3;
+
+VACUUM ANALYZE starjoin_eager_h1, starjoin_eager_h2,
+               starjoin_eager_h3, starjoin_eager_hf;
+
+SET max_parallel_workers_per_gather = 0;
+-- Use a small work_mem, so that the hash joins to h2 and h3 need multiple
+-- batches.
+SET work_mem = '400kB';
+
+-- With the GUC on, hf is never joined to h2 and h3 before h1, the first
+-- dimension in the canonical order, so the partial aggregation (grouping by
+-- hf.d1) can't be done below the join to h1, unlike with the GUC off.
+
+-- eager agg, GROUP BY first dim (h1), GUC on
+SET enable_starjoin_ordering = on;
+SELECT pg_temp.starjoin_explain($$
+SELECT h1.v, sum(hf.x)
+FROM starjoin_eager_hf AS hf JOIN starjoin_eager_h1 AS h1 ON hf.d1 = h1.id
+                             JOIN starjoin_eager_h2 AS h2 ON hf.d2 = h2.id
+                             JOIN starjoin_eager_h3 AS h3 ON hf.d3 = h3.id
+GROUP BY h1.v
+$$) AS "QUERY PLAN";
+
+-- eager agg, GROUP BY first dim (h1), GUC off
+SET enable_starjoin_ordering = off;
+SELECT pg_temp.starjoin_explain($$
+SELECT h1.v, sum(hf.x)
+FROM starjoin_eager_hf AS hf JOIN starjoin_eager_h1 AS h1 ON hf.d1 = h1.id
+                             JOIN starjoin_eager_h2 AS h2 ON hf.d2 = h2.id
+                             JOIN starjoin_eager_h3 AS h3 ON hf.d3 = h3.id
+GROUP BY h1.v
+$$) AS "QUERY PLAN";
+
+-- With h1 last in FROM, and so also last in the canonical order, the partial
+-- aggregation is done below the join to h1 with the GUC on too.
+
+-- same query, h1 written last in FROM, GUC on
+SET enable_starjoin_ordering = on;
+SELECT pg_temp.starjoin_explain($$
+SELECT h1.v, sum(hf.x)
+FROM starjoin_eager_hf AS hf JOIN starjoin_eager_h2 AS h2 ON hf.d2 = h2.id
+                             JOIN starjoin_eager_h3 AS h3 ON hf.d3 = h3.id
+                             JOIN starjoin_eager_h1 AS h1 ON hf.d1 = h1.id
+GROUP BY h1.v
+$$) AS "QUERY PLAN";
+
+-- same query, h1 written last in FROM, GUC off
+SET enable_starjoin_ordering = off;
+SELECT pg_temp.starjoin_explain($$
+SELECT h1.v, sum(hf.x)
+FROM starjoin_eager_hf AS hf JOIN starjoin_eager_h2 AS h2 ON hf.d2 = h2.id
+                             JOIN starjoin_eager_h3 AS h3 ON hf.d3 = h3.id
+                             JOIN starjoin_eager_h1 AS h1 ON hf.d1 = h1.id
+GROUP BY h1.v
+$$) AS "QUERY PLAN";
+
+DROP TABLE starjoin_eager_hf, starjoin_eager_h1, starjoin_eager_h2, starjoin_eager_h3;
diff --git a/src/test/regress/sql/starjoin_other.sql b/src/test/regress/sql/starjoin_other.sql
new file mode 100644
index 00000000000..2eed24ab491
--- /dev/null
+++ b/src/test/regress/sql/starjoin_other.sql
@@ -0,0 +1,422 @@
+--
+-- Checks for various other cases with enable_starjoin_ordering (the
+-- planning failures are covered by starjoin_reproducers).
+--
+-- Each check is a single boolean, so that the output does not depend on
+-- platform-specific costs or memory usage.  Some checks show known
+-- limitations, where the plan with the GUC enabled is worse.
+--
+-- Some checks are about the planning effort (the number of join rels the
+-- join search builds), which is not visible in SQL.  Those checks compare the
+-- planner memory usage reported by EXPLAIN (MEMORY), which is proportional
+-- to the number of join rels and paths.
+--
+
+SET max_parallel_workers_per_gather = 0;
+
+-- total cost of the plan, with enable_starjoin_ordering enabled/disabled
+CREATE FUNCTION starjoin_other_cost(query text, starjoin bool) RETURNS float8
+LANGUAGE plpgsql AS $$
+DECLARE
+  plan json;
+BEGIN
+  PERFORM set_config('enable_starjoin_ordering', starjoin::text, true);
+  EXECUTE 'EXPLAIN (FORMAT JSON) ' || query INTO plan;
+  RETURN (plan->0->'Plan'->>'Total Cost')::float8;
+END;
+$$;
+
+-- memory used by the planner (in kB), with enable_starjoin_ordering
+-- enabled/disabled
+CREATE FUNCTION starjoin_other_memory(query text, starjoin bool) RETURNS bigint
+LANGUAGE plpgsql AS $$
+DECLARE
+  plan json;
+BEGIN
+  PERFORM set_config('enable_starjoin_ordering', starjoin::text, true);
+  EXECUTE 'EXPLAIN (MEMORY, FORMAT JSON) ' || query INTO plan;
+  RETURN (plan->0->'Planning'->>'Memory Used')::bigint;
+END;
+$$;
+
+-- the plan (without costs), with enable_starjoin_ordering enabled/disabled
+CREATE FUNCTION starjoin_other_plan(query text, starjoin bool) RETURNS text
+LANGUAGE plpgsql AS $$
+DECLARE
+  plan json;
+BEGIN
+  PERFORM set_config('enable_starjoin_ordering', starjoin::text, true);
+  EXECUTE 'EXPLAIN (COSTS OFF, FORMAT JSON) ' || query INTO plan;
+  RETURN plan::text;
+END;
+$$;
+
+-- star with 3 dimensions (same as in starjoin_plan)
+CREATE TABLE starjoin_other_p1 (id int PRIMARY KEY, v int, w int) WITH (autovacuum_enabled = off);
+CREATE TABLE starjoin_other_p2 (id int PRIMARY KEY, v int, w int) WITH (autovacuum_enabled = off);
+CREATE TABLE starjoin_other_p3 (id int PRIMARY KEY, v int, w int) WITH (autovacuum_enabled = off);
+
+INSERT INTO starjoin_other_p1 SELECT i, i % 100, i FROM generate_series(1, 1000) i;
+INSERT INTO starjoin_other_p2 SELECT i, i % 100, i FROM generate_series(1, 1000) i;
+INSERT INTO starjoin_other_p3 SELECT i, i % 100, i FROM generate_series(1, 1000) i;
+
+CREATE TABLE starjoin_other_pf (id int PRIMARY KEY, d1 int NOT NULL,
+  d2 int NOT NULL, d3 int NOT NULL, x int) WITH (autovacuum_enabled = off);
+
+INSERT INTO starjoin_other_pf
+SELECT i, 1 + (i * 7) % 1000, 1 + (i * 13) % 1000, 1 + (i * 17) % 1000, i % 1000
+  FROM generate_series(1, 20000) i;
+
+-- add the foreign keys after loading the data (faster than checking each row)
+ALTER TABLE starjoin_other_pf
+  ADD FOREIGN KEY (d1) REFERENCES starjoin_other_p1,
+  ADD FOREIGN KEY (d2) REFERENCES starjoin_other_p2,
+  ADD FOREIGN KEY (d3) REFERENCES starjoin_other_p3;
+
+-- star with two wide dimensions and a large narrow one (same as in
+-- starjoin_width)
+CREATE TABLE starjoin_other_wa (id int PRIMARY KEY, t text) WITH (autovacuum_enabled = off);
+CREATE TABLE starjoin_other_wb (id int PRIMARY KEY, t text) WITH (autovacuum_enabled = off);
+CREATE TABLE starjoin_other_wc (id int PRIMARY KEY, v int) WITH (autovacuum_enabled = off);
+
+INSERT INTO starjoin_other_wa SELECT i, repeat(md5(i::text), 16) FROM generate_series(1, 100) i;
+INSERT INTO starjoin_other_wb SELECT i, repeat(md5(i::text), 16) FROM generate_series(1, 100) i;
+INSERT INTO starjoin_other_wc SELECT i, i FROM generate_series(1, 10000) i;
+
+CREATE TABLE starjoin_other_wf (id int, a int NOT NULL, b int NOT NULL,
+  c int NOT NULL) WITH (autovacuum_enabled = off);
+
+INSERT INTO starjoin_other_wf
+SELECT i, 1 + i % 100, 1 + (i * 7) % 100, 1 + (i * 13) % 10000
+  FROM generate_series(1, 10000) i;
+
+ALTER TABLE starjoin_other_wf
+  ADD FOREIGN KEY (a) REFERENCES starjoin_other_wa,
+  ADD FOREIGN KEY (b) REFERENCES starjoin_other_wb,
+  ADD FOREIGN KEY (c) REFERENCES starjoin_other_wc;
+
+-- star with a small dimension used in GROUP BY (same as in starjoin_eager)
+CREATE TABLE starjoin_other_h1 (id int PRIMARY KEY, v int) WITH (autovacuum_enabled = off);
+CREATE TABLE starjoin_other_h2 (id int PRIMARY KEY, v int) WITH (autovacuum_enabled = off);
+CREATE TABLE starjoin_other_h3 (id int PRIMARY KEY, v int) WITH (autovacuum_enabled = off);
+
+INSERT INTO starjoin_other_h1 SELECT i, i % 10 FROM generate_series(1, 100) i;
+INSERT INTO starjoin_other_h2 SELECT i, i FROM generate_series(1, 10000) i;
+INSERT INTO starjoin_other_h3 SELECT i, i FROM generate_series(1, 10000) i;
+
+CREATE TABLE starjoin_other_hf (id int, d1 int NOT NULL, d2 int NOT NULL,
+  d3 int NOT NULL, x int) WITH (autovacuum_enabled = off);
+
+INSERT INTO starjoin_other_hf
+SELECT i, 1 + i % 100, 1 + (i * 7) % 10000, 1 + (i * 13) % 10000, i % 1000
+  FROM generate_series(1, 20000) i;
+
+ALTER TABLE starjoin_other_hf
+  ADD FOREIGN KEY (d1) REFERENCES starjoin_other_h1,
+  ADD FOREIGN KEY (d2) REFERENCES starjoin_other_h2,
+  ADD FOREIGN KEY (d3) REFERENCES starjoin_other_h3;
+
+-- star with 10 dimensions d1-d10, a table "a" referenced by the fact, and 8
+-- tables c1-c8 joined on a non-unique column (all in the same equivalence
+-- class, so each pair of them can be joined)
+CREATE TABLE starjoin_other_a (id int PRIMARY KEY, v int) WITH (autovacuum_enabled = off);
+INSERT INTO starjoin_other_a SELECT i, i FROM generate_series(1, 100) i;
+
+DO $$
+BEGIN
+  FOR i IN 1..10 LOOP
+    EXECUTE format('CREATE TABLE starjoin_other_d%s (id int PRIMARY KEY, v int) WITH (autovacuum_enabled = off)', i);
+    EXECUTE format('INSERT INTO starjoin_other_d%s SELECT i, i FROM generate_series(1, 100) i', i);
+  END LOOP;
+  FOR i IN 1..8 LOOP
+    EXECUTE format('CREATE TABLE starjoin_other_c%s (id int PRIMARY KEY, v int) WITH (autovacuum_enabled = off)', i);
+    EXECUTE format('INSERT INTO starjoin_other_c%s SELECT i, i %% 50 FROM generate_series(1, 100) i', i);
+  END LOOP;
+END;
+$$;
+
+CREATE TABLE starjoin_other_f (id int PRIMARY KEY, a int NOT NULL,
+  d1 int NOT NULL, d2 int NOT NULL, d3 int NOT NULL, d4 int NOT NULL,
+  d5 int NOT NULL, d6 int NOT NULL, d7 int NOT NULL, d8 int NOT NULL,
+  d9 int NOT NULL, d10 int NOT NULL) WITH (autovacuum_enabled = off);
+
+INSERT INTO starjoin_other_f
+SELECT i, 1 + i % 100, 1 + (i * 3) % 100, 1 + (i * 7) % 100, 1 + (i * 11) % 100,
+       1 + (i * 13) % 100, 1 + (i * 17) % 100, 1 + (i * 19) % 100,
+       1 + (i * 23) % 100, 1 + (i * 29) % 100, 1 + (i * 31) % 100,
+       1 + (i * 37) % 100
+  FROM generate_series(1, 1000) i;
+
+ALTER TABLE starjoin_other_f
+  ADD FOREIGN KEY (a) REFERENCES starjoin_other_a,
+  ADD FOREIGN KEY (d1) REFERENCES starjoin_other_d1,
+  ADD FOREIGN KEY (d2) REFERENCES starjoin_other_d2,
+  ADD FOREIGN KEY (d3) REFERENCES starjoin_other_d3,
+  ADD FOREIGN KEY (d4) REFERENCES starjoin_other_d4,
+  ADD FOREIGN KEY (d5) REFERENCES starjoin_other_d5,
+  ADD FOREIGN KEY (d6) REFERENCES starjoin_other_d6,
+  ADD FOREIGN KEY (d7) REFERENCES starjoin_other_d7,
+  ADD FOREIGN KEY (d8) REFERENCES starjoin_other_d8,
+  ADD FOREIGN KEY (d9) REFERENCES starjoin_other_d9,
+  ADD FOREIGN KEY (d10) REFERENCES starjoin_other_d10;
+
+VACUUM ANALYZE starjoin_other_p1, starjoin_other_p2, starjoin_other_p3,
+  starjoin_other_pf, starjoin_other_wa, starjoin_other_wb, starjoin_other_wc,
+  starjoin_other_wf, starjoin_other_h1, starjoin_other_h2, starjoin_other_h3,
+  starjoin_other_hf, starjoin_other_a, starjoin_other_d1, starjoin_other_d2,
+  starjoin_other_d3, starjoin_other_d4, starjoin_other_d5, starjoin_other_d6,
+  starjoin_other_d7, starjoin_other_d8, starjoin_other_d9, starjoin_other_d10,
+  starjoin_other_c1, starjoin_other_c2, starjoin_other_c3, starjoin_other_c4,
+  starjoin_other_c5, starjoin_other_c6, starjoin_other_c7, starjoin_other_c8,
+  starjoin_other_f;
+
+--
+-- Extra (non-FK) join clause between the fact and a dimension
+--
+-- The canonical order relies on each join to a dimension preserving the
+-- cardinality of the fact, so that all join orders of a cluster produce the
+-- same row counts.  But an additional join clause between the fact and the
+-- dimension (not matching the foreign key) makes the join selective, so the
+-- dimension should be joined first.  The cluster conditions check join
+-- clauses to other rels, but not additional join clauses to the fact.
+--
+SELECT $$
+SELECT count(*) FROM starjoin_other_pf AS pf
+  JOIN starjoin_other_p1 AS p1 ON pf.d1 = p1.id
+  JOIN starjoin_other_p2 AS p2 ON pf.d2 = p2.id
+  JOIN starjoin_other_p3 AS p3 ON pf.d3 = p3.id AND pf.x = p3.w
+$$ AS q_extra_clause \gset
+
+-- the canonical order joins p3 last, so the plan with the GUC enabled is
+-- more expensive
+SELECT starjoin_other_cost(:'q_extra_clause', true)
+       > starjoin_other_cost(:'q_extra_clause', false) * 1.01 AS extra_clause_cost_higher;
+
+--
+-- OR clause, from which extract_restriction_or_clauses() derives a
+-- restriction on the dimension, which excludes the dimension from the
+-- cluster (the clusters are built after extracting the restrictions)
+--
+SELECT $$
+SELECT count(*) FROM starjoin_other_pf AS pf
+  JOIN starjoin_other_p1 AS p1 ON pf.d1 = p1.id
+  JOIN starjoin_other_p2 AS p2 ON pf.d2 = p2.id
+  JOIN starjoin_other_p3 AS p3 ON pf.d3 = p3.id
+ WHERE (p3.w = 1 AND pf.x = 1) OR (p3.w = 2 AND pf.x = 2)
+$$ AS q_or_clause \gset
+
+SELECT starjoin_other_cost(:'q_or_clause', true)
+       <= starjoin_other_cost(:'q_or_clause', false) * 1.01 AS or_clause_cost_ok;
+
+--
+-- Pure FK joins, with dimensions of very different widths
+--
+-- Even if all joins preserve the cardinality, the join orders don't have the
+-- same cost.  With a small work_mem the hash join to the large dimension (wc)
+-- needs multiple batches, and the cost of batching depends on the width of
+-- the outer rows.  So it's much cheaper to join wc before the two wide
+-- dimensions, but wc is the last one in the canonical order.
+--
+SELECT $$
+SELECT wa.t, wb.t, wc.v FROM starjoin_other_wf AS wf
+  JOIN starjoin_other_wa AS wa ON wf.a = wa.id
+  JOIN starjoin_other_wb AS wb ON wf.b = wb.id
+  JOIN starjoin_other_wc AS wc ON wf.c = wc.id
+$$ AS q_width \gset
+
+-- Use 128kB, so that the hash join to wc needs multiple batches on all
+-- platforms.  With 256kB that's barely the case on 64-bit platforms (the
+-- hash table fits with work_mem of about 268kB), and not at all on 32-bit
+-- platforms, where the hash tuples are smaller and the hash table fits with
+-- less than 200kB.
+SET work_mem = '128kB';
+-- the canonical order joins wc last, so the plan with the GUC enabled is
+-- more expensive
+SELECT starjoin_other_cost(:'q_width', true)
+       > starjoin_other_cost(:'q_width', false) * 1.01 AS width_cost_higher;
+RESET work_mem;
+
+--
+-- Canonical pruning
+--
+-- Joins where one side has no cluster dimensions are not checked, so the
+-- join search still builds the 2-way joins of the fact with each dimension,
+-- and (fact, d2) + d1 passes the check too.  For the star with 10 dimensions
+-- the search builds 19 join rels instead of the 10 in the canonical order.
+-- Compare to planning the canonical order directly, forced by
+-- join_collapse_limit = 1 (the plans are the same).
+--
+SELECT $$
+SELECT count(*) FROM starjoin_other_f AS f
+  JOIN starjoin_other_d1 AS d1 ON f.d1 = d1.id
+  JOIN starjoin_other_d2 AS d2 ON f.d2 = d2.id
+  JOIN starjoin_other_d3 AS d3 ON f.d3 = d3.id
+  JOIN starjoin_other_d4 AS d4 ON f.d4 = d4.id
+  JOIN starjoin_other_d5 AS d5 ON f.d5 = d5.id
+  JOIN starjoin_other_d6 AS d6 ON f.d6 = d6.id
+  JOIN starjoin_other_d7 AS d7 ON f.d7 = d7.id
+  JOIN starjoin_other_d8 AS d8 ON f.d8 = d8.id
+  JOIN starjoin_other_d9 AS d9 ON f.d9 = d9.id
+  JOIN starjoin_other_d10 AS d10 ON f.d10 = d10.id
+$$ AS q_star \gset
+
+SET join_collapse_limit = 1;
+SELECT starjoin_other_plan(:'q_star', true) AS plan_canonical,
+       starjoin_other_memory(:'q_star', true) AS memory_canonical \gset
+
+-- a single subproblem with 11 rels (below geqo_threshold)
+SET join_collapse_limit = 20;
+SELECT starjoin_other_plan(:'q_star', true) = :'plan_canonical' AS flat_plan_canonical;
+-- XXX the search uses more memory than planning the canonical order
+SELECT starjoin_other_memory(:'q_star', true) <= :memory_canonical * 1.1 AS flat_search_canonical;
+RESET join_collapse_limit;
+
+--
+-- Outer joins and semijoins
+--
+-- Dimensions must not be part of any SpecialJoinInfo, but the check considers
+-- the syntactic relids (syn_lefthand/syn_righthand), not only the minimal
+-- ones.  So a LEFT JOIN or a semijoin (EXISTS) placed after the star joins
+-- disables the optimization, even if it references only the fact.  Writing
+-- the LEFT JOIN first works.  Each query has 8 rels (a single subproblem), and
+-- with the optimization the join search needs much less memory.
+--
+SELECT $$
+SELECT count(a.v) FROM starjoin_other_f AS f
+  LEFT JOIN starjoin_other_a AS a ON f.a = a.id
+  JOIN starjoin_other_d1 AS d1 ON f.d1 = d1.id
+  JOIN starjoin_other_d2 AS d2 ON f.d2 = d2.id
+  JOIN starjoin_other_d3 AS d3 ON f.d3 = d3.id
+  JOIN starjoin_other_d4 AS d4 ON f.d4 = d4.id
+  JOIN starjoin_other_d5 AS d5 ON f.d5 = d5.id
+  JOIN starjoin_other_d6 AS d6 ON f.d6 = d6.id
+$$ AS q_left_join_first \gset
+
+SELECT $$
+SELECT count(a.v) FROM starjoin_other_f AS f
+  JOIN starjoin_other_d1 AS d1 ON f.d1 = d1.id
+  JOIN starjoin_other_d2 AS d2 ON f.d2 = d2.id
+  JOIN starjoin_other_d3 AS d3 ON f.d3 = d3.id
+  JOIN starjoin_other_d4 AS d4 ON f.d4 = d4.id
+  JOIN starjoin_other_d5 AS d5 ON f.d5 = d5.id
+  JOIN starjoin_other_d6 AS d6 ON f.d6 = d6.id
+  LEFT JOIN starjoin_other_a AS a ON f.a = a.id
+$$ AS q_left_join_last \gset
+
+SELECT $$
+SELECT count(*) FROM starjoin_other_f AS f
+  JOIN starjoin_other_d1 AS d1 ON f.d1 = d1.id
+  JOIN starjoin_other_d2 AS d2 ON f.d2 = d2.id
+  JOIN starjoin_other_d3 AS d3 ON f.d3 = d3.id
+  JOIN starjoin_other_d4 AS d4 ON f.d4 = d4.id
+  JOIN starjoin_other_d5 AS d5 ON f.d5 = d5.id
+  JOIN starjoin_other_d6 AS d6 ON f.d6 = d6.id
+ WHERE EXISTS (SELECT 1 FROM starjoin_other_a AS a WHERE a.v = f.a)
+$$ AS q_exists \gset
+
+SELECT starjoin_other_memory(:'q_left_join_first', true)
+       < starjoin_other_memory(:'q_left_join_first', false) * 0.5 AS left_join_first_pruned;
+-- XXX no pruning with the LEFT JOIN at the end
+SELECT starjoin_other_memory(:'q_left_join_last', true)
+       < starjoin_other_memory(:'q_left_join_last', false) * 0.5 AS left_join_last_pruned;
+-- XXX no pruning with a semijoin
+SELECT starjoin_other_memory(:'q_exists', true)
+       < starjoin_other_memory(:'q_exists', false) * 0.5 AS exists_pruned;
+
+--
+-- Star split into subproblems
+--
+-- With the default join_collapse_limit, the star with 10 dimensions is split
+-- into two subproblems, and the canonical order is enforced in both.
+--
+SELECT starjoin_other_memory(:'q_star', true)
+       < starjoin_other_memory(:'q_star', false) * 0.5 AS split_search_pruned;
+
+--
+-- GEQO
+--
+-- The canonical order is enforced by GEQO too.
+--
+SET join_collapse_limit = 20;
+SET geqo_threshold = 8;
+-- GEQO uses the canonical order
+SELECT starjoin_other_plan(:'q_star', true) = :'plan_canonical' AS geqo_plan_canonical;
+RESET geqo_threshold;
+RESET join_collapse_limit;
+
+--
+-- Overhead in subproblems unrelated to the star
+--
+-- If the query has a cluster, the canonical order is checked for each join in
+-- all subproblems, including a large separate subproblem (8 rels joinable in
+-- any order).  With only two dimensions there's nothing to prune in the star,
+-- so the planning should not use more memory with the GUC enabled (e.g. if
+-- the check leaked memory).
+--
+SELECT $$
+SELECT count(*)
+  FROM (starjoin_other_f AS f
+        JOIN starjoin_other_d1 AS d1 ON f.d1 = d1.id
+        JOIN starjoin_other_d2 AS d2 ON f.d2 = d2.id)
+  JOIN (starjoin_other_c1 AS c1
+        JOIN starjoin_other_c2 AS c2 ON c1.v = c2.v
+        JOIN starjoin_other_c3 AS c3 ON c2.v = c3.v
+        JOIN starjoin_other_c4 AS c4 ON c3.v = c4.v
+        JOIN starjoin_other_c5 AS c5 ON c4.v = c5.v
+        JOIN starjoin_other_c6 AS c6 ON c5.v = c6.v
+        JOIN starjoin_other_c7 AS c7 ON c6.v = c7.v
+        JOIN starjoin_other_c8 AS c8 ON c7.v = c8.v) ON f.id = c1.id
+$$ AS q_subproblems \gset
+
+SELECT starjoin_other_memory(:'q_subproblems', true)
+       <= starjoin_other_memory(:'q_subproblems', false) * 1.01 AS subproblems_memory_ok;
+
+--
+-- Eager aggregation
+--
+-- With GROUP BY on a column of a dimension (h1), eager aggregation can place
+-- a partial aggregate on the join of the fact and the other dimensions, and
+-- then join h1.  With the canonical order that join rel is only built if h1
+-- is the last dimension, so the plan depends on the order of the dimensions
+-- in the FROM clause.
+--
+SELECT $$
+SELECT h1.v, sum(hf.x) FROM starjoin_other_hf AS hf
+  JOIN starjoin_other_h1 AS h1 ON hf.d1 = h1.id
+  JOIN starjoin_other_h2 AS h2 ON hf.d2 = h2.id
+  JOIN starjoin_other_h3 AS h3 ON hf.d3 = h3.id
+ GROUP BY h1.v
+$$ AS q_eager_first \gset
+
+SELECT $$
+SELECT h1.v, sum(hf.x) FROM starjoin_other_hf AS hf
+  JOIN starjoin_other_h2 AS h2 ON hf.d2 = h2.id
+  JOIN starjoin_other_h3 AS h3 ON hf.d3 = h3.id
+  JOIN starjoin_other_h1 AS h1 ON hf.d1 = h1.id
+ GROUP BY h1.v
+$$ AS q_eager_last \gset
+
+SELECT starjoin_other_plan(:'q_eager_first', false)
+       LIKE '%"Partial Mode": "Partial"%' AS eager_first_partial_agg_off;
+-- the canonical order joins h1 first, so there's no partial aggregate with
+-- the GUC enabled
+SELECT starjoin_other_plan(:'q_eager_first', true)
+       LIKE '%"Partial Mode": "Partial"%' AS eager_first_partial_agg_on;
+SELECT starjoin_other_plan(:'q_eager_last', true)
+       LIKE '%"Partial Mode": "Partial"%' AS eager_last_partial_agg_on;
+
+RESET max_parallel_workers_per_gather;
+
+DROP FUNCTION starjoin_other_cost(text, bool);
+DROP FUNCTION starjoin_other_memory(text, bool);
+DROP FUNCTION starjoin_other_plan(text, bool);
+
+DROP TABLE starjoin_other_pf, starjoin_other_p1, starjoin_other_p2,
+  starjoin_other_p3, starjoin_other_wf, starjoin_other_wa, starjoin_other_wb,
+  starjoin_other_wc, starjoin_other_hf, starjoin_other_h1, starjoin_other_h2,
+  starjoin_other_h3, starjoin_other_f, starjoin_other_a, starjoin_other_d1,
+  starjoin_other_d2, starjoin_other_d3, starjoin_other_d4, starjoin_other_d5,
+  starjoin_other_d6, starjoin_other_d7, starjoin_other_d8, starjoin_other_d9,
+  starjoin_other_d10, starjoin_other_c1, starjoin_other_c2, starjoin_other_c3,
+  starjoin_other_c4, starjoin_other_c5, starjoin_other_c6, starjoin_other_c7,
+  starjoin_other_c8;
diff --git a/src/test/regress/sql/starjoin_plan.sql b/src/test/regress/sql/starjoin_plan.sql
new file mode 100644
index 00000000000..569130d39fa
--- /dev/null
+++ b/src/test/regress/sql/starjoin_plan.sql
@@ -0,0 +1,92 @@
+--
+-- STARJOIN_PLAN
+-- Test star join ordering with extra join quals between fact and dimension
+--
+
+-- Ignore platform-dependent memory and hash sizing, but retain the
+-- distinction between single-batch and multi-batch hashing.
+CREATE OR REPLACE FUNCTION pg_temp.starjoin_explain(query text) RETURNS SETOF text
+LANGUAGE plpgsql AS $$
+DECLARE
+  ln text;
+BEGIN
+  FOR ln IN EXECUTE
+    'EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, BUFFERS OFF, SUMMARY OFF) ' || query
+  LOOP
+    ln := regexp_replace(ln, '\m\d+kB', 'NkB', 'g');
+    ln := regexp_replace(ln, 'Buckets: \d+', 'Buckets: N');
+    ln := regexp_replace(ln, 'Batches: (?!1\M)\d+', 'Batches: multiple');
+    ln := regexp_replace(ln, ' \(originally \d+\)', '', 'g');
+    RETURN NEXT ln;
+  END LOOP;
+END;
+$$;
+
+CREATE TABLE starjoin_plan_p1 (id int PRIMARY KEY, v int, w int);
+CREATE TABLE starjoin_plan_p2 (id int PRIMARY KEY, v int, w int);
+CREATE TABLE starjoin_plan_p3 (id int PRIMARY KEY, v int, w int);
+
+INSERT INTO starjoin_plan_p1 SELECT i, i % 100, i FROM generate_series(1,1000) i;
+INSERT INTO starjoin_plan_p2 SELECT i, i % 100, i FROM generate_series(1,1000) i;
+INSERT INTO starjoin_plan_p3 SELECT i, i % 100, i FROM generate_series(1,1000) i;
+
+CREATE TABLE starjoin_plan_pf (id int PRIMARY KEY,
+  d1 int NOT NULL REFERENCES starjoin_plan_p1,
+  d2 int NOT NULL REFERENCES starjoin_plan_p2,
+  d3 int NOT NULL REFERENCES starjoin_plan_p3,
+  x int);
+
+INSERT INTO starjoin_plan_pf SELECT i, 1 + (i * 7) % 1000, 1 + (i * 13) % 1000, 1 + (i * 17) % 1000, i % 1000
+  FROM generate_series(1,20000) i;
+
+VACUUM ANALYZE starjoin_plan_p1, starjoin_plan_p2, starjoin_plan_p3, starjoin_plan_pf;
+
+SET max_parallel_workers_per_gather = 0;
+
+-- Q1: extra (non-FK) join qual between fact and the last dimension. It makes
+-- the join to p3 selective, but p3 is still a dimension, so with the GUC on
+-- p3 is joined last, while with the GUC off it's joined first.
+
+-- join the fact to p1, p2 and p3, with an extra join qual for p3, GUC on
+SET enable_starjoin_ordering = on;
+SELECT pg_temp.starjoin_explain($$
+SELECT count(*) FROM starjoin_plan_pf AS pf
+  JOIN starjoin_plan_p1 AS p1 ON pf.d1 = p1.id
+  JOIN starjoin_plan_p2 AS p2 ON pf.d2 = p2.id
+  JOIN starjoin_plan_p3 AS p3 ON pf.d3 = p3.id AND pf.x = p3.w
+$$) AS "QUERY PLAN";
+
+-- same query, GUC off
+SET enable_starjoin_ordering = off;
+SELECT pg_temp.starjoin_explain($$
+SELECT count(*) FROM starjoin_plan_pf AS pf
+  JOIN starjoin_plan_p1 AS p1 ON pf.d1 = p1.id
+  JOIN starjoin_plan_p2 AS p2 ON pf.d2 = p2.id
+  JOIN starjoin_plan_p3 AS p3 ON pf.d3 = p3.id AND pf.x = p3.w
+$$) AS "QUERY PLAN";
+
+-- Q2: OR clause from which extract_restriction_or_clauses() derives a
+-- restriction on p3, so p3 is not a dimension (the clusters are built after
+-- deriving the restrictions), and the plan is the same as with the GUC off.
+
+-- join the fact to p1, p2 and p3, with an OR clause in WHERE, GUC on
+SET enable_starjoin_ordering = on;
+SELECT pg_temp.starjoin_explain($$
+SELECT count(*) FROM starjoin_plan_pf AS pf
+  JOIN starjoin_plan_p1 AS p1 ON pf.d1 = p1.id
+  JOIN starjoin_plan_p2 AS p2 ON pf.d2 = p2.id
+  JOIN starjoin_plan_p3 AS p3 ON pf.d3 = p3.id
+ WHERE (p3.w = 1 AND pf.x = 1) OR (p3.w = 2 AND pf.x = 2)
+$$) AS "QUERY PLAN";
+
+-- same query, GUC off
+SET enable_starjoin_ordering = off;
+SELECT pg_temp.starjoin_explain($$
+SELECT count(*) FROM starjoin_plan_pf AS pf
+  JOIN starjoin_plan_p1 AS p1 ON pf.d1 = p1.id
+  JOIN starjoin_plan_p2 AS p2 ON pf.d2 = p2.id
+  JOIN starjoin_plan_p3 AS p3 ON pf.d3 = p3.id
+ WHERE (p3.w = 1 AND pf.x = 1) OR (p3.w = 2 AND pf.x = 2)
+$$) AS "QUERY PLAN";
+
+DROP TABLE starjoin_plan_pf, starjoin_plan_p1, starjoin_plan_p2, starjoin_plan_p3;
diff --git a/src/test/regress/sql/starjoin_plan_large.sql b/src/test/regress/sql/starjoin_plan_large.sql
new file mode 100644
index 00000000000..fa912e14b75
--- /dev/null
+++ b/src/test/regress/sql/starjoin_plan_large.sql
@@ -0,0 +1,92 @@
+--
+-- STARJOIN_PLAN_LARGE
+-- Same as starjoin_plan, but with larger tables (expensive)
+--
+
+-- Ignore platform-dependent memory and hash sizing, but retain the
+-- distinction between single-batch and multi-batch hashing.
+CREATE OR REPLACE FUNCTION pg_temp.starjoin_explain(query text) RETURNS SETOF text
+LANGUAGE plpgsql AS $$
+DECLARE
+  ln text;
+BEGIN
+  FOR ln IN EXECUTE
+    'EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, BUFFERS OFF, SUMMARY OFF) ' || query
+  LOOP
+    ln := regexp_replace(ln, '\m\d+kB', 'NkB', 'g');
+    ln := regexp_replace(ln, 'Buckets: \d+', 'Buckets: N');
+    ln := regexp_replace(ln, 'Batches: (?!1\M)\d+', 'Batches: multiple');
+    ln := regexp_replace(ln, ' \(originally \d+\)', '', 'g');
+    RETURN NEXT ln;
+  END LOOP;
+END;
+$$;
+
+CREATE TABLE starjoin_plan_p1 (id int PRIMARY KEY, v int, w int);
+CREATE TABLE starjoin_plan_p2 (id int PRIMARY KEY, v int, w int);
+CREATE TABLE starjoin_plan_p3 (id int PRIMARY KEY, v int, w int);
+
+INSERT INTO starjoin_plan_p1 SELECT i, i % 100, i FROM generate_series(1,10000) i;
+INSERT INTO starjoin_plan_p2 SELECT i, i % 100, i FROM generate_series(1,10000) i;
+INSERT INTO starjoin_plan_p3 SELECT i, i % 100, i FROM generate_series(1,10000) i;
+
+CREATE TABLE starjoin_plan_pf (id int PRIMARY KEY,
+  d1 int NOT NULL REFERENCES starjoin_plan_p1,
+  d2 int NOT NULL REFERENCES starjoin_plan_p2,
+  d3 int NOT NULL REFERENCES starjoin_plan_p3,
+  x int);
+
+INSERT INTO starjoin_plan_pf SELECT i, 1 + (i * 7) % 10000, 1 + (i * 13) % 10000, 1 + (i * 17) % 10000, i % 1000
+  FROM generate_series(1,200000) i;
+
+VACUUM ANALYZE starjoin_plan_p1, starjoin_plan_p2, starjoin_plan_p3, starjoin_plan_pf;
+
+SET max_parallel_workers_per_gather = 0;
+
+-- Q1: extra (non-FK) join qual between fact and the last dimension. It makes
+-- the join to p3 selective, but p3 is still a dimension, so with the GUC on
+-- p3 is joined last, while with the GUC off it's joined first.
+
+-- join the fact to p1, p2 and p3, with an extra join qual for p3, GUC on
+SET enable_starjoin_ordering = on;
+SELECT pg_temp.starjoin_explain($$
+SELECT count(*) FROM starjoin_plan_pf AS pf
+  JOIN starjoin_plan_p1 AS p1 ON pf.d1 = p1.id
+  JOIN starjoin_plan_p2 AS p2 ON pf.d2 = p2.id
+  JOIN starjoin_plan_p3 AS p3 ON pf.d3 = p3.id AND pf.x = p3.w
+$$) AS "QUERY PLAN";
+
+-- same query, GUC off
+SET enable_starjoin_ordering = off;
+SELECT pg_temp.starjoin_explain($$
+SELECT count(*) FROM starjoin_plan_pf AS pf
+  JOIN starjoin_plan_p1 AS p1 ON pf.d1 = p1.id
+  JOIN starjoin_plan_p2 AS p2 ON pf.d2 = p2.id
+  JOIN starjoin_plan_p3 AS p3 ON pf.d3 = p3.id AND pf.x = p3.w
+$$) AS "QUERY PLAN";
+
+-- Q2: OR clause from which extract_restriction_or_clauses() derives a
+-- restriction on p3, so p3 is not a dimension (the clusters are built after
+-- deriving the restrictions), and the plan is the same as with the GUC off.
+
+-- join the fact to p1, p2 and p3, with an OR clause in WHERE, GUC on
+SET enable_starjoin_ordering = on;
+SELECT pg_temp.starjoin_explain($$
+SELECT count(*) FROM starjoin_plan_pf AS pf
+  JOIN starjoin_plan_p1 AS p1 ON pf.d1 = p1.id
+  JOIN starjoin_plan_p2 AS p2 ON pf.d2 = p2.id
+  JOIN starjoin_plan_p3 AS p3 ON pf.d3 = p3.id
+ WHERE (p3.w = 1 AND pf.x = 1) OR (p3.w = 2 AND pf.x = 2)
+$$) AS "QUERY PLAN";
+
+-- same query, GUC off
+SET enable_starjoin_ordering = off;
+SELECT pg_temp.starjoin_explain($$
+SELECT count(*) FROM starjoin_plan_pf AS pf
+  JOIN starjoin_plan_p1 AS p1 ON pf.d1 = p1.id
+  JOIN starjoin_plan_p2 AS p2 ON pf.d2 = p2.id
+  JOIN starjoin_plan_p3 AS p3 ON pf.d3 = p3.id
+ WHERE (p3.w = 1 AND pf.x = 1) OR (p3.w = 2 AND pf.x = 2)
+$$) AS "QUERY PLAN";
+
+DROP TABLE starjoin_plan_pf, starjoin_plan_p1, starjoin_plan_p2, starjoin_plan_p3;
diff --git a/src/test/regress/sql/starjoin_planning.sql b/src/test/regress/sql/starjoin_planning.sql
new file mode 100644
index 00000000000..210e94bf8c0
--- /dev/null
+++ b/src/test/regress/sql/starjoin_planning.sql
@@ -0,0 +1,163 @@
+--
+-- STARJOIN_PLANNING
+-- Test star join ordering with the join search split into sub-problems
+--
+
+CREATE TABLE starjoin_planning_d0 (id int PRIMARY KEY, v int);
+CREATE TABLE starjoin_planning_d1 (id int PRIMARY KEY, v int);
+CREATE TABLE starjoin_planning_d2 (id int PRIMARY KEY, v int);
+CREATE TABLE starjoin_planning_d3 (id int PRIMARY KEY, v int);
+CREATE TABLE starjoin_planning_d4 (id int PRIMARY KEY, v int);
+CREATE TABLE starjoin_planning_d5 (id int PRIMARY KEY, v int);
+CREATE TABLE starjoin_planning_d6 (id int PRIMARY KEY, v int);
+CREATE TABLE starjoin_planning_d7 (id int PRIMARY KEY, v int);
+
+CREATE TABLE starjoin_planning_f (id int PRIMARY KEY,
+  d0 int NOT NULL REFERENCES starjoin_planning_d0,
+  d1 int NOT NULL REFERENCES starjoin_planning_d1,
+  d2 int NOT NULL REFERENCES starjoin_planning_d2,
+  d3 int NOT NULL REFERENCES starjoin_planning_d3,
+  d4 int NOT NULL REFERENCES starjoin_planning_d4,
+  d5 int NOT NULL REFERENCES starjoin_planning_d5,
+  d6 int NOT NULL REFERENCES starjoin_planning_d6,
+  d7 int NOT NULL REFERENCES starjoin_planning_d7,
+  x int);
+
+-- Tests A-H check that planning does not fail with "failed to build any N-way
+-- joins" when the canonical order can't be followed in a sub-problem, because
+-- some cluster members are not in the sub-problem, or were already joined in
+-- a lower sub-problem.
+
+-- A: explicit join order, sub-problem has fact + non-prefix dims, because d1
+-- (the first dimension in the canonical order) is joined only in the upper
+-- sub-problem
+SET join_collapse_limit = 1;
+
+-- join the fact to d2 and d3, and then the result to d1
+EXPLAIN (COSTS OFF) SELECT * FROM starjoin_planning_d1 AS d1 JOIN (starjoin_planning_f AS f JOIN starjoin_planning_d2 AS d2 ON f.d2 = d2.id JOIN starjoin_planning_d3 AS d3 ON f.d3 = d3.id) ON f.d1 = d1.id;
+
+-- B: explicit join order, sub-problem has dims but no fact, so the dims can
+-- be joined only by a cartesian product
+
+-- join the fact to the cartesian product of d1 and d2, GUC on
+SET enable_starjoin_ordering = on;
+EXPLAIN (COSTS OFF) SELECT * FROM starjoin_planning_f AS f JOIN (starjoin_planning_d1 AS d1 CROSS JOIN starjoin_planning_d2 AS d2) ON f.d1 = d1.id AND f.d2 = d2.id;
+
+-- same query, GUC off
+SET enable_starjoin_ordering = off;
+EXPLAIN (COSTS OFF) SELECT * FROM starjoin_planning_f AS f JOIN (starjoin_planning_d1 AS d1 CROSS JOIN starjoin_planning_d2 AS d2) ON f.d1 = d1.id AND f.d2 = d2.id;
+
+RESET enable_starjoin_ordering;
+RESET join_collapse_limit;
+
+-- C: default settings, 9 rels, join_collapse_limit (8) splits the problem,
+-- and d0 (the first dimension) is joined only in the upper sub-problem
+
+-- join the fact to d1-d7, and then the result to d0
+EXPLAIN (COSTS OFF) SELECT count(*) FROM starjoin_planning_d0 AS d0 JOIN (starjoin_planning_f AS f
+  JOIN starjoin_planning_d1 AS d1 ON f.d1 = d1.id
+  JOIN starjoin_planning_d2 AS d2 ON f.d2 = d2.id
+  JOIN starjoin_planning_d3 AS d3 ON f.d3 = d3.id
+  JOIN starjoin_planning_d4 AS d4 ON f.d4 = d4.id
+  JOIN starjoin_planning_d5 AS d5 ON f.d5 = d5.id
+  JOIN starjoin_planning_d6 AS d6 ON f.d6 = d6.id
+  JOIN starjoin_planning_d7 AS d7 ON f.d7 = d7.id) ON f.d0 = d0.id;
+
+-- D: default settings, view + outer dimension, split the same way as in C
+CREATE VIEW starjoin_planning_star AS
+SELECT f.*, d1.v AS v1, d2.v AS v2, d3.v AS v3, d4.v AS v4, d5.v AS v5, d6.v AS v6, d7.v AS v7
+  FROM starjoin_planning_f AS f JOIN starjoin_planning_d1 AS d1 ON f.d1 = d1.id
+                                JOIN starjoin_planning_d2 AS d2 ON f.d2 = d2.id
+                                JOIN starjoin_planning_d3 AS d3 ON f.d3 = d3.id
+                                JOIN starjoin_planning_d4 AS d4 ON f.d4 = d4.id
+                                JOIN starjoin_planning_d5 AS d5 ON f.d5 = d5.id
+                                JOIN starjoin_planning_d6 AS d6 ON f.d6 = d6.id
+                                JOIN starjoin_planning_d7 AS d7 ON f.d7 = d7.id;
+
+-- join the view (the fact joined to d1-d7) to d0, GUC on
+EXPLAIN (COSTS OFF) SELECT count(*) FROM starjoin_planning_d0 AS d0 JOIN starjoin_planning_star s ON s.d0 = d0.id;
+
+-- same query, GUC off
+SET enable_starjoin_ordering = off;
+EXPLAIN (COSTS OFF) SELECT count(*) FROM starjoin_planning_d0 AS d0 JOIN starjoin_planning_star s ON s.d0 = d0.id;
+RESET enable_starjoin_ordering;
+
+-- E: default settings, comma FROM list with a pulled-up subquery, which
+-- from_collapse_limit keeps as a separate sub-problem with dims but no fact
+
+-- comma FROM list joining the fact to d0-d5, and to a subquery with the
+-- cartesian product of d6 and d7
+EXPLAIN (COSTS OFF) SELECT count(*) FROM starjoin_planning_f AS f, starjoin_planning_d0 AS d0,
+  starjoin_planning_d1 AS d1, starjoin_planning_d2 AS d2, starjoin_planning_d3 AS d3,
+  starjoin_planning_d4 AS d4, starjoin_planning_d5 AS d5,
+  (SELECT d6.id AS i6, d7.id AS i7 FROM starjoin_planning_d6 AS d6, starjoin_planning_d7 AS d7) s
+ WHERE f.d0 = d0.id AND f.d1 = d1.id AND f.d2 = d2.id AND f.d3 = d3.id
+   AND f.d4 = d4.id AND f.d5 = d5.id AND f.d6 = s.i6 AND f.d7 = s.i7;
+
+-- F: from_collapse_limit, the fact is joined to a dimension (with a higher
+-- relid than the other dimensions) in a separate subproblem, i.e. before the
+-- other dimensions, contrary to the canonical order
+SET from_collapse_limit = 3;
+
+-- comma FROM list with d1, d2 and the fact joined to d3
+EXPLAIN (COSTS OFF) SELECT count(*) FROM starjoin_planning_d1 AS d1, starjoin_planning_d2 AS d2,
+  starjoin_planning_f AS f JOIN starjoin_planning_d3 AS d3 ON f.d3 = d3.id
+ WHERE f.d1 = d1.id AND f.d2 = d2.id;
+RESET from_collapse_limit;
+
+-- G: same, but with default settings (9 rels exceed from_collapse_limit)
+
+-- comma FROM list with d0-d6 and the fact joined to d7
+EXPLAIN (COSTS OFF) SELECT count(*) FROM starjoin_planning_d0 AS d0,
+  starjoin_planning_d1 AS d1, starjoin_planning_d2 AS d2, starjoin_planning_d3 AS d3,
+  starjoin_planning_d4 AS d4, starjoin_planning_d5 AS d5, starjoin_planning_d6 AS d6,
+  starjoin_planning_f AS f JOIN starjoin_planning_d7 AS d7 ON f.d7 = d7.id
+ WHERE f.d0 = d0.id AND f.d1 = d1.id AND f.d2 = d2.id AND f.d3 = d3.id
+   AND f.d4 = d4.id AND f.d5 = d5.id AND f.d6 = d6.id;
+
+-- H: join_collapse_limit, right-nested explicit joins, so the fact is joined
+-- to d3 and d4 in a separate sub-problem, before d1 and d2, contrary to the
+-- canonical order
+SET join_collapse_limit = 3;
+
+-- join the fact to d3 and d4, then the result to d2, and then to d1
+EXPLAIN (COSTS OFF) SELECT count(*) FROM starjoin_planning_d1 AS d1
+  JOIN (starjoin_planning_d2 AS d2
+        JOIN (starjoin_planning_f AS f
+              JOIN starjoin_planning_d3 AS d3 ON f.d3 = d3.id
+              JOIN starjoin_planning_d4 AS d4 ON f.d4 = d4.id)
+        ON f.d2 = d2.id)
+  ON f.d1 = d1.id;
+RESET join_collapse_limit;
+
+-- I: explicit join order, sub-problem has dimensions but no fact, so the
+-- canonical order is not enforced and the cartesian products may start with
+-- the small dimensions (d2, d3), just like with the GUC off
+INSERT INTO starjoin_planning_d1 SELECT i, i FROM generate_series(1, 1000) i;
+INSERT INTO starjoin_planning_d2 VALUES (1, 1), (2, 2);
+INSERT INTO starjoin_planning_d3 VALUES (1, 1), (2, 2);
+ANALYZE starjoin_planning_d1, starjoin_planning_d2, starjoin_planning_d3;
+
+SET join_collapse_limit = 3;
+
+-- join the fact to the cartesian product of d1, d2 and d3, GUC on
+SET enable_starjoin_ordering = on;
+EXPLAIN (COSTS OFF) SELECT count(*) FROM starjoin_planning_f AS f
+  JOIN (starjoin_planning_d1 AS d1 CROSS JOIN starjoin_planning_d2 AS d2
+        CROSS JOIN starjoin_planning_d3 AS d3)
+  ON f.d1 = d1.id AND f.d2 = d2.id AND f.d3 = d3.id;
+
+-- same query, GUC off
+SET enable_starjoin_ordering = off;
+EXPLAIN (COSTS OFF) SELECT count(*) FROM starjoin_planning_f AS f
+  JOIN (starjoin_planning_d1 AS d1 CROSS JOIN starjoin_planning_d2 AS d2
+        CROSS JOIN starjoin_planning_d3 AS d3)
+  ON f.d1 = d1.id AND f.d2 = d2.id AND f.d3 = d3.id;
+
+RESET enable_starjoin_ordering;
+RESET join_collapse_limit;
+
+DROP VIEW starjoin_planning_star;
+DROP TABLE starjoin_planning_f, starjoin_planning_d0, starjoin_planning_d1,
+  starjoin_planning_d2, starjoin_planning_d3, starjoin_planning_d4,
+  starjoin_planning_d5, starjoin_planning_d6, starjoin_planning_d7;
diff --git a/src/test/regress/sql/starjoin_reproducers.sql b/src/test/regress/sql/starjoin_reproducers.sql
new file mode 100644
index 00000000000..a833c10fcbb
--- /dev/null
+++ b/src/test/regress/sql/starjoin_reproducers.sql
@@ -0,0 +1,326 @@
+--
+-- Planning queries with enable_starjoin_ordering, where the join search
+-- can't simply follow the canonical order
+--
+-- In queries A-I, the clusters (determined for the whole query) and the join
+-- search subproblems (sub-joinlists, determined by
+-- join_collapse_limit/from_collapse_limit, explicit joins, views and
+-- subqueries) do not align, so the canonical order can't be followed in some
+-- subproblem.  The canonical-order check must not reject all joins the
+-- subproblem can build, otherwise the planning fails with "ERROR:  failed to
+-- build any N-way joins".
+--
+-- In query J, the last-ditch pass joins dimensions to rels without the fact,
+-- and two such rels then get joined.
+--
+-- For each query, show the plan with the GUC enabled, and then check that
+-- the query returns the same result with the GUC enabled and disabled.
+--
+
+CREATE TABLE starjoin_reproducers_d0 (id int PRIMARY KEY, v int) WITH (autovacuum_enabled = off);
+CREATE TABLE starjoin_reproducers_d1 (id int PRIMARY KEY, v int) WITH (autovacuum_enabled = off);
+CREATE TABLE starjoin_reproducers_d2 (id int PRIMARY KEY, v int) WITH (autovacuum_enabled = off);
+CREATE TABLE starjoin_reproducers_d3 (id int PRIMARY KEY, v int) WITH (autovacuum_enabled = off);
+CREATE TABLE starjoin_reproducers_d4 (id int PRIMARY KEY, v int) WITH (autovacuum_enabled = off);
+CREATE TABLE starjoin_reproducers_d5 (id int PRIMARY KEY, v int) WITH (autovacuum_enabled = off);
+CREATE TABLE starjoin_reproducers_d6 (id int PRIMARY KEY, v int) WITH (autovacuum_enabled = off);
+CREATE TABLE starjoin_reproducers_d7 (id int PRIMARY KEY, v int) WITH (autovacuum_enabled = off);
+
+CREATE TABLE starjoin_reproducers_f (id int PRIMARY KEY,
+  d0 int NOT NULL REFERENCES starjoin_reproducers_d0,
+  d1 int NOT NULL REFERENCES starjoin_reproducers_d1,
+  d2 int NOT NULL REFERENCES starjoin_reproducers_d2,
+  d3 int NOT NULL REFERENCES starjoin_reproducers_d3,
+  d4 int NOT NULL REFERENCES starjoin_reproducers_d4,
+  d5 int NOT NULL REFERENCES starjoin_reproducers_d5,
+  d6 int NOT NULL REFERENCES starjoin_reproducers_d6,
+  d7 int NOT NULL REFERENCES starjoin_reproducers_d7,
+  x int) WITH (autovacuum_enabled = off);
+
+INSERT INTO starjoin_reproducers_d0 SELECT i, i FROM generate_series(1, 10) i;
+INSERT INTO starjoin_reproducers_d1 SELECT i, 10 * i FROM generate_series(1, 20) i;
+INSERT INTO starjoin_reproducers_d2 SELECT i, 100 * i FROM generate_series(1, 30) i;
+INSERT INTO starjoin_reproducers_d3 SELECT i, 1000 * i FROM generate_series(1, 40) i;
+INSERT INTO starjoin_reproducers_d4 SELECT i, i FROM generate_series(1, 50) i;
+INSERT INTO starjoin_reproducers_d5 SELECT i, 10 * i FROM generate_series(1, 60) i;
+INSERT INTO starjoin_reproducers_d6 SELECT i, 100 * i FROM generate_series(1, 70) i;
+INSERT INTO starjoin_reproducers_d7 SELECT i, 1000 * i FROM generate_series(1, 80) i;
+
+INSERT INTO starjoin_reproducers_f
+SELECT i, 1 + i % 10, 1 + (i * 3) % 20, 1 + (i * 7) % 30, 1 + (i * 11) % 40,
+       1 + (i * 13) % 50, 1 + (i * 17) % 60, 1 + (i * 19) % 70, 1 + (i * 23) % 80, i
+  FROM generate_series(1, 500) i;
+
+-- small table for the outer joins (used by J)
+CREATE TABLE starjoin_reproducers_t (a int, b int) WITH (autovacuum_enabled = off);
+INSERT INTO starjoin_reproducers_t SELECT i % 2, i % 3 FROM generate_series(1, 4) i;
+
+VACUUM ANALYZE starjoin_reproducers_d0, starjoin_reproducers_d1,
+  starjoin_reproducers_d2, starjoin_reproducers_d3, starjoin_reproducers_d4,
+  starjoin_reproducers_d5, starjoin_reproducers_d6, starjoin_reproducers_d7,
+  starjoin_reproducers_f, starjoin_reproducers_t;
+
+-- star over the fact and dimensions d1-d7 (used by D)
+CREATE VIEW starjoin_reproducers_star AS
+SELECT f.*, d1.v AS v1, d2.v AS v2, d3.v AS v3, d4.v AS v4, d5.v AS v5,
+       d6.v AS v6, d7.v AS v7
+  FROM starjoin_reproducers_f AS f
+  JOIN starjoin_reproducers_d1 AS d1 ON f.d1 = d1.id
+  JOIN starjoin_reproducers_d2 AS d2 ON f.d2 = d2.id
+  JOIN starjoin_reproducers_d3 AS d3 ON f.d3 = d3.id
+  JOIN starjoin_reproducers_d4 AS d4 ON f.d4 = d4.id
+  JOIN starjoin_reproducers_d5 AS d5 ON f.d5 = d5.id
+  JOIN starjoin_reproducers_d6 AS d6 ON f.d6 = d6.id
+  JOIN starjoin_reproducers_d7 AS d7 ON f.d7 = d7.id;
+
+-- fact joined to a single dimension d7 (used by H)
+CREATE VIEW starjoin_reproducers_fv AS
+SELECT f.*, d7.v AS v7
+  FROM starjoin_reproducers_f AS f
+  JOIN starjoin_reproducers_d7 AS d7 ON f.d7 = d7.id;
+
+-- run the query with the GUC enabled and disabled, return both results
+CREATE FUNCTION starjoin_reproducers_check(query text,
+                                           OUT starjoin_on text,
+                                           OUT starjoin_off text)
+LANGUAGE plpgsql AS $$
+BEGIN
+  PERFORM set_config('enable_starjoin_ordering', 'on', true);
+  EXECUTE format('SELECT row(q.*)::text FROM (%s) q', query) INTO starjoin_on;
+  PERFORM set_config('enable_starjoin_ordering', 'off', true);
+  EXECUTE format('SELECT row(q.*)::text FROM (%s) q', query) INTO starjoin_off;
+END;
+$$;
+
+SET enable_starjoin_ordering = on;
+
+-- A: explicit join order, the subproblem has the fact and dimensions that are
+-- not a prefix of the canonical order (d1 is joined in the upper subproblem)
+SET join_collapse_limit = 1;
+EXPLAIN (COSTS OFF)
+SELECT count(*), sum(d1.v + d2.v + d3.v)
+  FROM starjoin_reproducers_d1 AS d1
+  JOIN (starjoin_reproducers_f AS f
+        JOIN starjoin_reproducers_d2 AS d2 ON f.d2 = d2.id
+        JOIN starjoin_reproducers_d3 AS d3 ON f.d3 = d3.id) ON f.d1 = d1.id;
+SELECT * FROM starjoin_reproducers_check($$
+SELECT count(*), sum(d1.v + d2.v + d3.v)
+  FROM starjoin_reproducers_d1 AS d1
+  JOIN (starjoin_reproducers_f AS f
+        JOIN starjoin_reproducers_d2 AS d2 ON f.d2 = d2.id
+        JOIN starjoin_reproducers_d3 AS d3 ON f.d3 = d3.id) ON f.d1 = d1.id
+$$);
+
+-- B: explicit join order, the subproblem has dimensions but not the fact
+EXPLAIN (COSTS OFF)
+SELECT count(*), sum(d1.v + d2.v)
+  FROM starjoin_reproducers_f AS f
+  JOIN (starjoin_reproducers_d1 AS d1 CROSS JOIN starjoin_reproducers_d2 AS d2)
+    ON f.d1 = d1.id AND f.d2 = d2.id;
+SELECT * FROM starjoin_reproducers_check($$
+SELECT count(*), sum(d1.v + d2.v)
+  FROM starjoin_reproducers_f AS f
+  JOIN (starjoin_reproducers_d1 AS d1 CROSS JOIN starjoin_reproducers_d2 AS d2)
+    ON f.d1 = d1.id AND f.d2 = d2.id
+$$);
+RESET join_collapse_limit;
+
+-- C: default settings, 9 rels, join_collapse_limit splits the problem, and
+-- the first dimension (d0) is joined in the upper subproblem
+EXPLAIN (COSTS OFF)
+SELECT count(*), sum(d0.v + d7.v)
+  FROM starjoin_reproducers_d0 AS d0
+  JOIN (starjoin_reproducers_f AS f
+        JOIN starjoin_reproducers_d1 AS d1 ON f.d1 = d1.id
+        JOIN starjoin_reproducers_d2 AS d2 ON f.d2 = d2.id
+        JOIN starjoin_reproducers_d3 AS d3 ON f.d3 = d3.id
+        JOIN starjoin_reproducers_d4 AS d4 ON f.d4 = d4.id
+        JOIN starjoin_reproducers_d5 AS d5 ON f.d5 = d5.id
+        JOIN starjoin_reproducers_d6 AS d6 ON f.d6 = d6.id
+        JOIN starjoin_reproducers_d7 AS d7 ON f.d7 = d7.id) ON f.d0 = d0.id;
+SELECT * FROM starjoin_reproducers_check($$
+SELECT count(*), sum(d0.v + d7.v)
+  FROM starjoin_reproducers_d0 AS d0
+  JOIN (starjoin_reproducers_f AS f
+        JOIN starjoin_reproducers_d1 AS d1 ON f.d1 = d1.id
+        JOIN starjoin_reproducers_d2 AS d2 ON f.d2 = d2.id
+        JOIN starjoin_reproducers_d3 AS d3 ON f.d3 = d3.id
+        JOIN starjoin_reproducers_d4 AS d4 ON f.d4 = d4.id
+        JOIN starjoin_reproducers_d5 AS d5 ON f.d5 = d5.id
+        JOIN starjoin_reproducers_d6 AS d6 ON f.d6 = d6.id
+        JOIN starjoin_reproducers_d7 AS d7 ON f.d7 = d7.id) ON f.d0 = d0.id
+$$);
+
+-- D: default settings, view over the star, joined to another dimension
+EXPLAIN (COSTS OFF)
+SELECT count(*), sum(d0.v + s.v1 + s.v7)
+  FROM starjoin_reproducers_d0 AS d0
+  JOIN starjoin_reproducers_star AS s ON s.d0 = d0.id;
+SELECT * FROM starjoin_reproducers_check($$
+SELECT count(*), sum(d0.v + s.v1 + s.v7)
+  FROM starjoin_reproducers_d0 AS d0
+  JOIN starjoin_reproducers_star AS s ON s.d0 = d0.id
+$$);
+
+-- E: default settings, FROM list with a pulled-up subquery, split by
+-- from_collapse_limit
+EXPLAIN (COSTS OFF)
+SELECT count(*), sum(d0.v + s.v6 + s.v7)
+  FROM starjoin_reproducers_f AS f,
+       starjoin_reproducers_d0 AS d0, starjoin_reproducers_d1 AS d1,
+       starjoin_reproducers_d2 AS d2, starjoin_reproducers_d3 AS d3,
+       starjoin_reproducers_d4 AS d4, starjoin_reproducers_d5 AS d5,
+       (SELECT d6.id AS i6, d6.v AS v6, d7.id AS i7, d7.v AS v7
+          FROM starjoin_reproducers_d6 AS d6,
+               starjoin_reproducers_d7 AS d7) AS s
+ WHERE f.d0 = d0.id AND f.d1 = d1.id AND f.d2 = d2.id AND f.d3 = d3.id
+   AND f.d4 = d4.id AND f.d5 = d5.id AND f.d6 = s.i6 AND f.d7 = s.i7;
+SELECT * FROM starjoin_reproducers_check($$
+SELECT count(*), sum(d0.v + s.v6 + s.v7)
+  FROM starjoin_reproducers_f AS f,
+       starjoin_reproducers_d0 AS d0, starjoin_reproducers_d1 AS d1,
+       starjoin_reproducers_d2 AS d2, starjoin_reproducers_d3 AS d3,
+       starjoin_reproducers_d4 AS d4, starjoin_reproducers_d5 AS d5,
+       (SELECT d6.id AS i6, d6.v AS v6, d7.id AS i7, d7.v AS v7
+          FROM starjoin_reproducers_d6 AS d6,
+               starjoin_reproducers_d7 AS d7) AS s
+ WHERE f.d0 = d0.id AND f.d1 = d1.id AND f.d2 = d2.id AND f.d3 = d3.id
+   AND f.d4 = d4.id AND f.d5 = d5.id AND f.d6 = s.i6 AND f.d7 = s.i7
+$$);
+
+-- F: from_collapse_limit = 3, FROM list with an explicit join of the fact
+-- and a dimension with higher relid than the dimensions in the FROM list
+SET from_collapse_limit = 3;
+EXPLAIN (COSTS OFF)
+SELECT count(*), sum(d1.v + d2.v + d3.v)
+  FROM starjoin_reproducers_d1 AS d1, starjoin_reproducers_d2 AS d2,
+       starjoin_reproducers_f AS f
+       JOIN starjoin_reproducers_d3 AS d3 ON f.d3 = d3.id
+ WHERE f.d1 = d1.id AND f.d2 = d2.id;
+SELECT * FROM starjoin_reproducers_check($$
+SELECT count(*), sum(d1.v + d2.v + d3.v)
+  FROM starjoin_reproducers_d1 AS d1, starjoin_reproducers_d2 AS d2,
+       starjoin_reproducers_f AS f
+       JOIN starjoin_reproducers_d3 AS d3 ON f.d3 = d3.id
+ WHERE f.d1 = d1.id AND f.d2 = d2.id
+$$);
+RESET from_collapse_limit;
+
+-- G: default settings, 7 dimensions in the FROM list, and an explicit join
+-- of the fact and the last dimension (9 rels > from_collapse_limit)
+EXPLAIN (COSTS OFF)
+SELECT count(*), sum(d0.v + d6.v + d7.v)
+  FROM starjoin_reproducers_d0 AS d0, starjoin_reproducers_d1 AS d1,
+       starjoin_reproducers_d2 AS d2, starjoin_reproducers_d3 AS d3,
+       starjoin_reproducers_d4 AS d4, starjoin_reproducers_d5 AS d5,
+       starjoin_reproducers_d6 AS d6,
+       starjoin_reproducers_f AS f
+       JOIN starjoin_reproducers_d7 AS d7 ON f.d7 = d7.id
+ WHERE f.d0 = d0.id AND f.d1 = d1.id AND f.d2 = d2.id AND f.d3 = d3.id
+   AND f.d4 = d4.id AND f.d5 = d5.id AND f.d6 = d6.id;
+SELECT * FROM starjoin_reproducers_check($$
+SELECT count(*), sum(d0.v + d6.v + d7.v)
+  FROM starjoin_reproducers_d0 AS d0, starjoin_reproducers_d1 AS d1,
+       starjoin_reproducers_d2 AS d2, starjoin_reproducers_d3 AS d3,
+       starjoin_reproducers_d4 AS d4, starjoin_reproducers_d5 AS d5,
+       starjoin_reproducers_d6 AS d6,
+       starjoin_reproducers_f AS f
+       JOIN starjoin_reproducers_d7 AS d7 ON f.d7 = d7.id
+ WHERE f.d0 = d0.id AND f.d1 = d1.id AND f.d2 = d2.id AND f.d3 = d3.id
+   AND f.d4 = d4.id AND f.d5 = d5.id AND f.d6 = d6.id
+$$);
+
+-- H: default settings, view over the fact and the last dimension, joined to
+-- the 7 other dimensions
+EXPLAIN (COSTS OFF)
+SELECT count(*), sum(d0.v + d6.v + fv.v7)
+  FROM starjoin_reproducers_d0 AS d0, starjoin_reproducers_d1 AS d1,
+       starjoin_reproducers_d2 AS d2, starjoin_reproducers_d3 AS d3,
+       starjoin_reproducers_d4 AS d4, starjoin_reproducers_d5 AS d5,
+       starjoin_reproducers_d6 AS d6, starjoin_reproducers_fv AS fv
+ WHERE fv.d0 = d0.id AND fv.d1 = d1.id AND fv.d2 = d2.id AND fv.d3 = d3.id
+   AND fv.d4 = d4.id AND fv.d5 = d5.id AND fv.d6 = d6.id;
+SELECT * FROM starjoin_reproducers_check($$
+SELECT count(*), sum(d0.v + d6.v + fv.v7)
+  FROM starjoin_reproducers_d0 AS d0, starjoin_reproducers_d1 AS d1,
+       starjoin_reproducers_d2 AS d2, starjoin_reproducers_d3 AS d3,
+       starjoin_reproducers_d4 AS d4, starjoin_reproducers_d5 AS d5,
+       starjoin_reproducers_d6 AS d6, starjoin_reproducers_fv AS fv
+ WHERE fv.d0 = d0.id AND fv.d1 = d1.id AND fv.d2 = d2.id AND fv.d3 = d3.id
+   AND fv.d4 = d4.id AND fv.d5 = d5.id AND fv.d6 = d6.id
+$$);
+
+-- I: join_collapse_limit = 3, right-nested explicit joins
+SET join_collapse_limit = 3;
+EXPLAIN (COSTS OFF)
+SELECT count(*), sum(d1.v + d2.v + d3.v + d4.v)
+  FROM starjoin_reproducers_d1 AS d1
+  JOIN (starjoin_reproducers_d2 AS d2
+        JOIN (starjoin_reproducers_f AS f
+              JOIN starjoin_reproducers_d3 AS d3 ON f.d3 = d3.id
+              JOIN starjoin_reproducers_d4 AS d4 ON f.d4 = d4.id)
+          ON f.d2 = d2.id)
+    ON f.d1 = d1.id;
+SELECT * FROM starjoin_reproducers_check($$
+SELECT count(*), sum(d1.v + d2.v + d3.v + d4.v)
+  FROM starjoin_reproducers_d1 AS d1
+  JOIN (starjoin_reproducers_d2 AS d2
+        JOIN (starjoin_reproducers_f AS f
+              JOIN starjoin_reproducers_d3 AS d3 ON f.d3 = d3.id
+              JOIN starjoin_reproducers_d4 AS d4 ON f.d4 = d4.id)
+          ON f.d2 = d2.id)
+    ON f.d1 = d1.id
+$$);
+RESET join_collapse_limit;
+
+-- J: from_collapse_limit = 9, the subquery is a separate subproblem with the
+-- star (the fact has a join clause only to w, outside the subquery) and two
+-- outer joins of three rels each, linked by a non-strict clause between their
+-- nullable sides.  Nothing can be joined at level 4, so the last-ditch pass
+-- joins the outer joins to dimensions, and the clause then joins those rels.
+SET from_collapse_limit = 9;
+EXPLAIN (COSTS OFF)
+SELECT count(*)
+  FROM starjoin_reproducers_t AS w,
+       (SELECT f.x
+          FROM starjoin_reproducers_f AS f
+          JOIN starjoin_reproducers_d1 AS d1 ON f.d1 = d1.id
+          JOIN starjoin_reproducers_d2 AS d2 ON f.d2 = d2.id,
+               starjoin_reproducers_t AS p
+          LEFT JOIN (starjoin_reproducers_t AS q
+                     JOIN starjoin_reproducers_t AS q2 ON q.a = q2.a)
+            ON p.a = q.a,
+               starjoin_reproducers_t AS s
+          LEFT JOIN (starjoin_reproducers_t AS t
+                     JOIN starjoin_reproducers_t AS t2 ON t.a = t2.a)
+            ON s.a = t.a
+         WHERE f.id <= 10 AND coalesce(q.b, 0) = coalesce(t.b, 0)) AS sub
+ WHERE sub.x = w.a;
+SELECT * FROM starjoin_reproducers_check($$
+SELECT count(*)
+  FROM starjoin_reproducers_t AS w,
+       (SELECT f.x
+          FROM starjoin_reproducers_f AS f
+          JOIN starjoin_reproducers_d1 AS d1 ON f.d1 = d1.id
+          JOIN starjoin_reproducers_d2 AS d2 ON f.d2 = d2.id,
+               starjoin_reproducers_t AS p
+          LEFT JOIN (starjoin_reproducers_t AS q
+                     JOIN starjoin_reproducers_t AS q2 ON q.a = q2.a)
+            ON p.a = q.a,
+               starjoin_reproducers_t AS s
+          LEFT JOIN (starjoin_reproducers_t AS t
+                     JOIN starjoin_reproducers_t AS t2 ON t.a = t2.a)
+            ON s.a = t.a
+         WHERE f.id <= 10 AND coalesce(q.b, 0) = coalesce(t.b, 0)) AS sub
+ WHERE sub.x = w.a
+$$);
+RESET from_collapse_limit;
+
+RESET enable_starjoin_ordering;
+
+DROP FUNCTION starjoin_reproducers_check(text);
+DROP VIEW starjoin_reproducers_star, starjoin_reproducers_fv;
+DROP TABLE starjoin_reproducers_f, starjoin_reproducers_d0,
+  starjoin_reproducers_d1, starjoin_reproducers_d2, starjoin_reproducers_d3,
+  starjoin_reproducers_d4, starjoin_reproducers_d5, starjoin_reproducers_d6,
+  starjoin_reproducers_d7, starjoin_reproducers_t;
diff --git a/src/test/regress/sql/starjoin_width.sql b/src/test/regress/sql/starjoin_width.sql
new file mode 100644
index 00000000000..45a37a88869
--- /dev/null
+++ b/src/test/regress/sql/starjoin_width.sql
@@ -0,0 +1,60 @@
+--
+-- STARJOIN_WIDTH
+-- Test star join ordering with dimensions of very different widths
+--
+
+-- Ignore platform-dependent memory and hash sizing, but retain the
+-- distinction between single-batch and multi-batch hashing.
+CREATE OR REPLACE FUNCTION pg_temp.starjoin_explain(query text) RETURNS SETOF text
+LANGUAGE plpgsql AS $$
+DECLARE
+  ln text;
+BEGIN
+  FOR ln IN EXECUTE
+    'EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, BUFFERS OFF, SUMMARY OFF) ' || query
+  LOOP
+    ln := regexp_replace(ln, '\m\d+kB', 'NkB', 'g');
+    ln := regexp_replace(ln, 'Buckets: \d+', 'Buckets: N');
+    ln := regexp_replace(ln, 'Batches: (?!1\M)\d+', 'Batches: multiple');
+    ln := regexp_replace(ln, ' \(originally \d+\)', '', 'g');
+    RETURN NEXT ln;
+  END LOOP;
+END;
+$$;
+
+CREATE TABLE starjoin_width_wa (id int PRIMARY KEY, t text);
+CREATE TABLE starjoin_width_wb (id int PRIMARY KEY, t text);
+CREATE TABLE starjoin_width_wc (id int PRIMARY KEY, v int);
+
+INSERT INTO starjoin_width_wa SELECT i, repeat(md5(i::text), 16) FROM generate_series(1,100) i;
+INSERT INTO starjoin_width_wb SELECT i, repeat(md5(i::text), 16) FROM generate_series(1,100) i;
+INSERT INTO starjoin_width_wc SELECT i, i FROM generate_series(1,10000) i;
+
+CREATE TABLE starjoin_width_wf (id int, a int NOT NULL REFERENCES starjoin_width_wa, b int NOT NULL REFERENCES starjoin_width_wb, c int NOT NULL REFERENCES starjoin_width_wc);
+
+INSERT INTO starjoin_width_wf SELECT i, 1 + i % 100, 1 + (i * 7) % 100, 1 + (i * 13) % 10000 FROM generate_series(1,10000) i;
+
+VACUUM ANALYZE starjoin_width_wa, starjoin_width_wb, starjoin_width_wc, starjoin_width_wf;
+
+SET max_parallel_workers_per_gather = 0;
+SET work_mem = '4MB';
+SET enable_nestloop = off; SET enable_mergejoin = off;
+
+-- All the joins preserve the cardinality, but the cost of a batched hash join
+-- depends on the width of the outer rows. So when the hash join to wc needs
+-- multiple batches (as in starjoin_width_large), the plan with the GUC off
+-- joins wc before the wide dimensions (wa, wb), while the canonical order
+-- joins it last. Otherwise the plans are the same.
+
+-- pure FK joins, GUC on
+SELECT pg_temp.starjoin_explain($$
+SELECT wa.t, wb.t, wc.v FROM starjoin_width_wf AS wf JOIN starjoin_width_wa AS wa ON wf.a = wa.id JOIN starjoin_width_wb AS wb ON wf.b = wb.id JOIN starjoin_width_wc AS wc ON wf.c = wc.id
+$$) AS "QUERY PLAN";
+
+-- pure FK joins, GUC off
+SET enable_starjoin_ordering = off;
+SELECT pg_temp.starjoin_explain($$
+SELECT wa.t, wb.t, wc.v FROM starjoin_width_wf AS wf JOIN starjoin_width_wa AS wa ON wf.a = wa.id JOIN starjoin_width_wb AS wb ON wf.b = wb.id JOIN starjoin_width_wc AS wc ON wf.c = wc.id
+$$) AS "QUERY PLAN";
+
+DROP TABLE starjoin_width_wf, starjoin_width_wa, starjoin_width_wb, starjoin_width_wc;
diff --git a/src/test/regress/sql/starjoin_width_large.sql b/src/test/regress/sql/starjoin_width_large.sql
new file mode 100644
index 00000000000..ea976b36e00
--- /dev/null
+++ b/src/test/regress/sql/starjoin_width_large.sql
@@ -0,0 +1,61 @@
+--
+-- STARJOIN_WIDTH_LARGE
+-- Same as starjoin_width, but with larger tables (expensive)
+--
+
+-- Ignore platform-dependent memory and hash sizing, but retain the
+-- distinction between single-batch and multi-batch hashing.
+CREATE OR REPLACE FUNCTION pg_temp.starjoin_explain(query text) RETURNS SETOF text
+LANGUAGE plpgsql AS $$
+DECLARE
+  ln text;
+BEGIN
+  FOR ln IN EXECUTE
+    'EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, BUFFERS OFF, SUMMARY OFF) ' || query
+  LOOP
+    ln := regexp_replace(ln, '\m\d+kB', 'NkB', 'g');
+    ln := regexp_replace(ln, 'Buckets: \d+', 'Buckets: N');
+    ln := regexp_replace(ln, 'Batches: (?!1\M)\d+', 'Batches: multiple');
+    ln := regexp_replace(ln, ' \(originally \d+\)', '', 'g');
+    RETURN NEXT ln;
+  END LOOP;
+END;
+$$;
+
+CREATE TABLE starjoin_width_wa (id int PRIMARY KEY, t text);
+CREATE TABLE starjoin_width_wb (id int PRIMARY KEY, t text);
+CREATE TABLE starjoin_width_wc (id int PRIMARY KEY, v int);
+
+INSERT INTO starjoin_width_wa SELECT i, repeat(md5(i::text), 16) FROM generate_series(1,100) i;
+INSERT INTO starjoin_width_wb SELECT i, repeat(md5(i::text), 16) FROM generate_series(1,100) i;
+INSERT INTO starjoin_width_wc SELECT i, i FROM generate_series(1,100000) i;
+
+CREATE TABLE starjoin_width_wf (id int, a int NOT NULL REFERENCES starjoin_width_wa, b int NOT NULL REFERENCES starjoin_width_wb, c int NOT NULL REFERENCES starjoin_width_wc);
+
+INSERT INTO starjoin_width_wf SELECT i, 1 + i % 100, 1 + (i * 7) % 100, 1 + (i * 13) % 100000 FROM generate_series(1,100000) i;
+
+VACUUM ANALYZE starjoin_width_wa, starjoin_width_wb, starjoin_width_wc, starjoin_width_wf;
+
+SET max_parallel_workers_per_gather = 0;
+-- Use a small work_mem, so that the hash join to wc needs multiple batches.
+SET work_mem = '400kB';
+SET enable_nestloop = off; SET enable_mergejoin = off;
+
+-- All the joins preserve the cardinality, but the cost of a batched hash join
+-- depends on the width of the outer rows. So when the hash join to wc needs
+-- multiple batches (as in starjoin_width_large), the plan with the GUC off
+-- joins wc before the wide dimensions (wa, wb), while the canonical order
+-- joins it last. Otherwise the plans are the same.
+
+-- pure FK joins, GUC on
+SELECT pg_temp.starjoin_explain($$
+SELECT wa.t, wb.t, wc.v FROM starjoin_width_wf AS wf JOIN starjoin_width_wa AS wa ON wf.a = wa.id JOIN starjoin_width_wb AS wb ON wf.b = wb.id JOIN starjoin_width_wc AS wc ON wf.c = wc.id
+$$) AS "QUERY PLAN";
+
+-- pure FK joins, GUC off
+SET enable_starjoin_ordering = off;
+SELECT pg_temp.starjoin_explain($$
+SELECT wa.t, wb.t, wc.v FROM starjoin_width_wf AS wf JOIN starjoin_width_wa AS wa ON wf.a = wa.id JOIN starjoin_width_wb AS wb ON wf.b = wb.id JOIN starjoin_width_wc AS wc ON wf.c = wc.id
+$$) AS "QUERY PLAN";
+
+DROP TABLE starjoin_width_wf, starjoin_width_wa, starjoin_width_wb, starjoin_width_wc;
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index f10eb469266..ed6bc82e912 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2987,6 +2987,7 @@ SplitTextOutputData
 SplitVar
 StackElem
 StakindFlags
+StarJoinClusterInfo
 StartBufferIOResult
 StartDataPtrType
 StartLOPtrType
-- 
2.56.1

