From 7e8a7c74c4e7312c38ccb7b9c4ceb8c129d411c1 Mon Sep 17 00:00:00 2001 From: Vlada Pogozhelskaya Date: Fri, 31 Jan 2025 11:16:28 +0700 Subject: [PATCH] Use uniqueness from group by for statistics estimation Tags: optimizer --- src/backend/utils/adt/selfuncs.c | 38 +++++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/src/backend/utils/adt/selfuncs.c b/src/backend/utils/adt/selfuncs.c index f48d61010c5..e85409c1ff8 100644 --- a/src/backend/utils/adt/selfuncs.c +++ b/src/backend/utils/adt/selfuncs.c @@ -5803,7 +5803,7 @@ examine_simple_variable(PlannerInfo *root, Var *var, * of learning something even with it. */ if (subquery->setOperations || - subquery->groupClause || + // subquery->groupClause || subquery->groupingSets) return; @@ -5839,6 +5839,42 @@ examine_simple_variable(PlannerInfo *root, Var *var, rte->eref->aliasname, var->varattno); var = (Var *) ste->expr; + if (subquery->groupClause) + { + List *groupVars = NIL; + List *targetVars = NIL; + ListCell *lc; + + /* Collect unique expressions from GROUP BY */ + foreach (lc, subquery->groupClause) + { + SortGroupClause *sgc = (SortGroupClause *) lfirst(lc); + TargetEntry *tle = get_sortgroupref_tle(sgc->tleSortGroupRef, subquery->targetList); + + if (tle && tle->expr) + groupVars = list_append_unique(groupVars, tle->expr); + } + + /* Collect unique expressions from the target list */ + foreach (lc, subquery->targetList) + { + TargetEntry *targetTle = (TargetEntry *) lfirst(lc); + if (targetTle && targetTle->expr) + targetVars = list_append_unique(targetVars, targetTle->expr); + } + + if (equal(groupVars, targetVars)) + { + vardata->isunique = true; + } + + list_free(groupVars); + list_free(targetVars); + } + + + + /* * If subquery uses DISTINCT, we can't make use of any stats for the * variable ... but, if it's the only DISTINCT column, we are entitled -- 2.46.0