Fixing grouping expressions inside subqueries

Tom Lane <tgl@sss.pgh.pa.us>

From: Tom Lane <tgl@sss.pgh.pa.us>
To: pgsql-hackers@lists.postgresql.org
Date: 2026-02-25T22:32:11Z
Lists: pgsql-hackers

Attachments

A recent complaint [1] reminded me of an unimplemented case that's
remained unimplemented for something close to 30 years.  It's
explained by this comment in parse_agg.c:

 * NOTE: we recognize grouping expressions in the main query, but only
 * grouping Vars in subqueries.  For example, this will be rejected,
 * although it could be allowed:
 *		SELECT
 *			(SELECT x FROM bar where y = (foo.a + foo.b))
 *		FROM foo
 *		GROUP BY a + b;
 * The difficulty is the need to account for different sublevels_up.
 * This appears to require a whole custom version of equal(), which is
 * way more pain than the feature seems worth.

Perhaps I was undercaffeinated when I wrote that, but anyway, there
is a way to do it that doesn't require either a custom version of
equal() or exponential amounts of time to do the matching.
See attached.

			regards, tom lane

[1] https://www.postgresql.org/message-id/flat/970600119.344834366.1772018068349.JavaMail.zimbra%40meteo.fr

Commits

  1. Support grouping-expression references and GROUPING() in subqueries.