diff --git a/src/backend/utils/adt/selfuncs.c b/src/backend/utils/adt/selfuncs.c index 08fa6774d9..2d5a1d8f41 100644 --- a/src/backend/utils/adt/selfuncs.c +++ b/src/backend/utils/adt/selfuncs.c @@ -5656,6 +5656,28 @@ examine_simple_variable(PlannerInfo *root, Var *var, subquery = subroot->parse; Assert(IsA(subquery, Query)); + /* Get the subquery output expression referenced by the upper Var */ + if (subquery->returningList) + subtlist = subquery->returningList; + else + subtlist = subquery->targetList; + ste = get_tle_by_resno(subtlist, var->varattno); + if (ste == NULL || ste->resjunk) + elog(ERROR, "subquery %s does not have attribute %d", + rte->eref->aliasname, var->varattno); + var = (Var *) ste->expr; + + /* + * If the subquery has a GROUP BY clause, we cannot rely on statistics + * for the column. However, if the GROUP BY contains only one column and + * the variable is present in the group list, we can consider it unique. + */ + if(subquery->groupClause) { + if (list_length(subquery->groupClause) == 1 && + targetIsInSortList(ste, InvalidOid, subquery->groupClause)) + vardata->isunique = true; + } + /* * Punt if subquery uses set operations or GROUP BY, as these will * mash underlying columns' stats beyond recognition. (Set ops are @@ -5669,17 +5691,6 @@ examine_simple_variable(PlannerInfo *root, Var *var, subquery->groupingSets) return; - /* Get the subquery output expression referenced by the upper Var */ - if (subquery->returningList) - subtlist = subquery->returningList; - else - subtlist = subquery->targetList; - ste = get_tle_by_resno(subtlist, var->varattno); - if (ste == NULL || ste->resjunk) - elog(ERROR, "subquery %s does not have attribute %d", - rte->eref->aliasname, var->varattno); - var = (Var *) ste->expr; - /* * 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