diff --git a/src/backend/utils/adt/selfuncs.c b/src/backend/utils/adt/selfuncs.c
index 5ee377595bd..2e3b98225df 100644
--- a/src/backend/utils/adt/selfuncs.c
+++ b/src/backend/utils/adt/selfuncs.c
@@ -127,6 +127,7 @@
 #include "utils/date.h"
 #include "utils/datum.h"
 #include "utils/fmgroids.h"
+#include "utils/hsearch.h"
 #include "utils/index_selfuncs.h"
 #include "utils/lsyscache.h"
 #include "utils/memutils.h"
@@ -3656,11 +3657,6 @@ matchingjoinsel(PG_FUNCTION_ARGS)
 }
 
 
-/*
- * Helper routine for estimate_num_groups: add an item to a list of
- * GroupVarInfos, but only if it's not known equal to any of the existing
- * entries.
- */
 typedef struct
 {
 	Node	   *var;			/* might be an expression, not just a Var */
@@ -3669,16 +3665,17 @@ typedef struct
 	bool		isdefault;		/* true if DEFAULT_NUM_DISTINCT was used */
 } GroupVarInfo;
 
-static List *
-add_unique_group_var(PlannerInfo *root, List *varinfos,
-					 Node *var, VariableStatData *vardata)
+/* The indexes identify both the grouping expressions and their relations. */
+typedef struct
 {
-	GroupVarInfo *varinfo;
-	double		ndistinct;
-	bool		isdefault;
-	ListCell   *lc;
+	EquivalenceClass *ec;		/* hash key */
+	List	   *indexes;		/* positions of GroupVarInfos in varinfos */
+} GroupVarECEntry;
 
-	ndistinct = get_variable_numdistinct(vardata, &isdefault);
+static GroupVarInfo *
+make_group_varinfo(PlannerInfo *root, Node *var, VariableStatData *vardata)
+{
+	GroupVarInfo *varinfo = palloc_object(GroupVarInfo);
 
 	/*
 	 * The nullingrels bits within the var could cause the same var to be
@@ -3687,45 +3684,166 @@ add_unique_group_var(PlannerInfo *root, List *varinfos,
 	 * extended statistics (see estimate_multivariate_ndistinct).  So strip
 	 * them out first.
 	 */
-	var = remove_nulling_relids(var, root->outer_join_rels, NULL);
+	varinfo->var = remove_nulling_relids(var, root->outer_join_rels, NULL);
+	varinfo->rel = vardata->rel;
+	varinfo->ndistinct = get_variable_numdistinct(vardata, &varinfo->isdefault);
+	return varinfo;
+}
+
+/*
+ * Consider the next grouping expression.  Leave NULLs in place of discarded
+ * items so that the indexes in ec_members remain valid throughout the scan.
+ */
+static void
+add_unique_group_var(List *varinfos, int index, List *eclasses,
+					 HTAB *ec_members, List **unmatched)
+{
+	ListCell   *cell = list_nth_cell(varinfos, index);
+	GroupVarInfo *varinfo = lfirst(cell);
+	List	   *entries = NIL;
+	Bitmapset  *matches = NULL;
+	int			i = -1;
+
+	foreach_ptr(EquivalenceClass, ec, eclasses)
+	{
+		foreach_ptr(EquivalenceMember, em, ec->ec_members)
+		{
+			GroupVarECEntry *entry;
+			bool		found;
+
+			Assert(!em->em_is_child);
+			if (!equal(varinfo->var, em->em_expr))
+				continue;
 
-	foreach(lc, varinfos)
+			entry = hash_search(ec_members, &ec, HASH_ENTER, &found);
+			if (!found)
+				entry->indexes = NIL;
+			entries = lappend(entries, entry);
+			break;
+		}
+	}
+
+	/* With no matching EC, only an exact duplicate can suppress this item. */
+	if (entries == NIL)
 	{
-		varinfo = (GroupVarInfo *) lfirst(lc);
+		if (list_member(*unmatched, varinfo->var))
+			lfirst(cell) = NULL;
+		else
+			*unmatched = lappend(*unmatched, varinfo->var);
+		return;
+	}
 
-		/* Drop exact duplicates */
-		if (equal(var, varinfo->var))
-			return varinfos;
+	/*
+	 * Visit matches in their original order, even if they came from several
+	 * ECs.  We can discard an older item before finding a later match that
+	 * makes us discard the new item too.
+	 */
+	foreach_ptr(GroupVarECEntry, entry, entries)
+	{
+		ListCell   *lc;
 
-		/*
-		 * Drop known-equal vars, but only if they belong to different
-		 * relations (see comments for estimate_num_groups).  We aren't too
-		 * fussy about the semantics of "equal" here.
-		 */
-		if (vardata->rel != varinfo->rel &&
-			exprs_known_equal(root, var, varinfo->var, InvalidOid))
+		foreach(lc, entry->indexes)
 		{
-			if (varinfo->ndistinct <= ndistinct)
-			{
-				/* Keep older item, forget new one */
-				return varinfos;
-			}
+			int			prev = lfirst_int(lc);
+
+			if (list_nth(varinfos, prev) == NULL)
+				entry->indexes = foreach_delete_current(entry->indexes, lc);
 			else
+				matches = bms_add_member(matches, prev);
+		}
+	}
+
+	while ((i = bms_next_member(matches, i)) >= 0)
+	{
+		ListCell   *prev = list_nth_cell(varinfos, i);
+		GroupVarInfo *old = lfirst(prev);
+
+		if (equal(varinfo->var, old->var) ||
+			(old->rel != varinfo->rel && old->ndistinct <= varinfo->ndistinct))
+		{
+			lfirst(cell) = NULL;
+			break;
+		}
+		if (old->rel != varinfo->rel)
+			lfirst(prev) = NULL;
+	}
+
+	if (lfirst(cell) != NULL)
+	{
+		foreach_ptr(GroupVarECEntry, entry, entries)
+			entry->indexes = lappend_int(entry->indexes, index);
+	}
+	list_free(entries);
+	bms_free(matches);
+}
+
+/* Remove redundant grouping expressions, preserving the survivors' order. */
+static List *
+get_unique_group_vars(PlannerInfo *root, List *varinfos)
+{
+	MemoryContext tmpcxt = NULL;
+	MemoryContext oldcxt = CurrentMemoryContext;
+	List	   *eclasses = NIL;
+	List	   *unmatched = NIL;
+	HTAB	   *ec_members = NULL;
+	GroupVarInfo *first;
+	int			nkeep = 0;
+
+	if (list_length(varinfos) < 2)
+		return varinfos;
+
+	/* ECs matter only for grouping expressions from different relations. */
+	first = linitial(varinfos);
+	foreach_ptr(GroupVarInfo, varinfo, varinfos)
+	{
+		if (varinfo->rel != first->rel)
+		{
+			/*
+			 * As in exprs_known_equal with InvalidOid, accept any opfamily
+			 * and even broken ECs, but never volatile ECs or child members.
+			 * Singleton ECs cannot prove different expressions equal.
+			 */
+			foreach_ptr(EquivalenceClass, ec, root->eq_classes)
 			{
-				/* Delete the older item */
-				varinfos = foreach_delete_current(varinfos, lc);
+				if (!ec->ec_has_volatile && list_length(ec->ec_members) > 1)
+					eclasses = lappend(eclasses, ec);
 			}
+			break;
 		}
 	}
 
-	varinfo = palloc_object(GroupVarInfo);
+	if (eclasses != NIL)
+	{
+		HASHCTL		ctl = {0};
 
-	varinfo->var = var;
-	varinfo->rel = vardata->rel;
-	varinfo->ndistinct = ndistinct;
-	varinfo->isdefault = isdefault;
-	varinfos = lappend(varinfos, varinfo);
-	return varinfos;
+		tmpcxt = AllocSetContextCreate(oldcxt, "grouping expressions",
+									   ALLOCSET_SMALL_SIZES);
+		MemoryContextSwitchTo(tmpcxt);
+		ctl.keysize = sizeof(EquivalenceClass *);
+		ctl.entrysize = sizeof(GroupVarECEntry);
+		ctl.hcxt = tmpcxt;
+		ec_members = hash_create("grouping EC members", 8, &ctl,
+								 HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
+	}
+
+	for (int i = 0; i < list_length(varinfos); i++)
+		add_unique_group_var(varinfos, i, eclasses, ec_members, &unmatched);
+
+	list_free(unmatched);
+	if (tmpcxt != NULL)
+	{
+		MemoryContextSwitchTo(oldcxt);
+		MemoryContextDelete(tmpcxt);
+	}
+	list_free(eclasses);
+
+	/* Compact the list now that we no longer need stable indexes. */
+	foreach_ptr(GroupVarInfo, varinfo, varinfos)
+	{
+		if (varinfo != NULL)
+			lfirst(list_nth_cell(varinfos, nkeep++)) = varinfo;
+	}
+	return list_truncate(varinfos, nkeep);
 }
 
 /*
@@ -3831,8 +3949,8 @@ estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows,
 
 	/*
 	 * Count groups derived from boolean grouping expressions.  For other
-	 * expressions, find the unique Vars used, treating an expression as a Var
-	 * if we can find stats for it.  For each one, record the statistical
+	 * expressions, collect the Vars used, treating an expression as a Var if
+	 * we can find stats for it.  For each one, record the statistical
 	 * estimate of number of distinct values (total in its table, without
 	 * regard for filtering).
 	 */
@@ -3889,8 +4007,8 @@ estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows,
 		examine_variable(root, groupexpr, 0, &vardata);
 		if (HeapTupleIsValid(vardata.statsTuple) || vardata.isunique)
 		{
-			varinfos = add_unique_group_var(root, varinfos,
-											groupexpr, &vardata);
+			varinfos = lappend(varinfos,
+							   make_group_varinfo(root, groupexpr, &vardata));
 			ReleaseVariableStats(vardata);
 			continue;
 		}
@@ -3928,11 +4046,13 @@ estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows,
 			Node	   *var = (Node *) lfirst(l2);
 
 			examine_variable(root, var, 0, &vardata);
-			varinfos = add_unique_group_var(root, varinfos, var, &vardata);
+			varinfos = lappend(varinfos, make_group_varinfo(root, var, &vardata));
 			ReleaseVariableStats(vardata);
 		}
 	}
 
+	varinfos = get_unique_group_vars(root, varinfos);
+
 	/*
 	 * If now no Vars, we must have an all-constant or all-boolean GROUP BY
 	 * list.
@@ -4266,7 +4386,7 @@ estimate_multivariate_bucketsize(PlannerInfo *root, RelOptInfo *inner,
 
 				/*
 				 * Clear nullingrels to correctly match hash keys.  See
-				 * add_unique_group_var()'s comment for details.
+				 * make_group_varinfo()'s comment for details.
 				 */
 				expr = remove_nulling_relids(expr, root->outer_join_rels, NULL);
 
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 278b2f3194b..a02c9d1b99e 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -1162,6 +1162,7 @@ GroupPath
 GroupPathExtraData
 GroupResultPath
 GroupState
+GroupVarECEntry
 GroupVarInfo
 GroupingExprInfo
 GroupingFunc
