diff --git a/src/backend/optimizer/path/equivclass.c b/src/backend/optimizer/path/equivclass.c
index b68a5a0ec7..d3d826b790 100644
--- a/src/backend/optimizer/path/equivclass.c
+++ b/src/backend/optimizer/path/equivclass.c
@@ -634,12 +634,6 @@ get_eclass_for_sort_expr(PlannerInfo *root,
 	 */
 	expr = canonicalize_ec_expression(expr, opcintype, collation);
 
-	/*
-	 * Get the precise set of nullable relids appearing in the expression.
-	 */
-	expr_relids = pull_varnos((Node *) expr);
-	nullable_relids = bms_intersect(nullable_relids, expr_relids);
-
 	/*
 	 * Scan through the existing EquivalenceClasses for a match
 	 */
@@ -716,6 +710,12 @@ get_eclass_for_sort_expr(PlannerInfo *root,
 	if (newec->ec_has_volatile && sortref == 0) /* should not happen */
 		elog(ERROR, "volatile EquivalenceClass has no sortref");
 
+	/*
+	 * Get the precise set of nullable relids appearing in the expression.
+	 */
+	expr_relids = pull_varnos((Node *) expr);
+	nullable_relids = bms_intersect(nullable_relids, expr_relids);
+
 	newem = add_eq_member(newec, copyObject(expr), expr_relids,
 						  nullable_relids, false, opcintype);
 
@@ -1171,9 +1171,9 @@ generate_join_implied_equalities(PlannerInfo *root,
 	}
 
 	/*
-	 * Get all eclasses in common between inner_rel's relids and outer_relids
+	 * Get all eclasses that mention both inner and outer sides of the join
 	 */
-	matching_ecs = get_common_eclass_indexes(root, inner_rel->relids,
+	matching_ecs = get_common_eclass_indexes(root, nominal_inner_relids,
 											 outer_relids);
 
 	i = -1;
