From f6b3f4eac7b7e71aa6df1e88736435df480aba6c Mon Sep 17 00:00:00 2001 From: William Bernbaum Date: Wed, 26 Aug 2026 08:16:06 -0700 Subject: [PATCH v2 04/17] Push a deduplication below the joins for DISTINCT Group on the DISTINCT clause when there is no GROUP BY. DISTINCT ON keeps a particular row from each group, so it does not qualify. --- src/backend/optimizer/plan/initsplan.c | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/src/backend/optimizer/plan/initsplan.c b/src/backend/optimizer/plan/initsplan.c index 5fe77ccdd68..d5a66f9c073 100644 --- a/src/backend/optimizer/plan/initsplan.c +++ b/src/backend/optimizer/plan/initsplan.c @@ -667,13 +667,17 @@ collect_eager_agg_infos(PlannerInfo *root) return; /* - * Don't apply eager aggregation if there are no available GROUP BY - * clauses. + * Identify the clauses that determine which rows the query can tell + * apart. DISTINCT serves the same purpose as GROUP BY here. DISTINCT ON + * does not, since it keeps a particular row from each group. */ - if (!root->processed_groupClause) - return; + if (root->processed_groupClause) + root->eager_group_clause = root->processed_groupClause; + else if (root->parse->distinctClause && !root->parse->hasDistinctOn) + root->eager_group_clause = root->processed_distinctClause; - root->eager_group_clause = root->processed_groupClause; + if (root->eager_group_clause == NIL) + return; /* * For now we don't try to support grouping sets. @@ -723,10 +727,10 @@ collect_eager_agg_infos(PlannerInfo *root) create_agg_clause_infos(root); /* - * If there are no suitable aggregate expressions, we cannot apply eager - * aggregation. + * If the query has aggregates, at least one must be suitable. With no + * aggregates, what gets pushed down is a plain deduplication. */ - if (root->agg_clause_list == NIL) + if (root->parse->hasAggs && root->agg_clause_list == NIL) return; /*