From 2337c110ad6543c41c17a82e2215487ad744f535 Mon Sep 17 00:00:00 2001 From: David Christensen Date: Sun, 29 Nov 2026 16:32:29 +0000 Subject: [PATCH v2 2/2] Add GROUP BY ALL GROUP BY ALL groups by every non-junk target-list entry that does not contain an aggregate of the current query level or a window function, making it exactly equivalent to spelling those expressions out in an explicit GROUP BY list. Window functions are skipped as the SQL standard directs. If no entries qualify, the clause is treated as GROUP BY (), so one row is returned even for empty input. This reimplements the feature reverted in a32733d8f10. The original commit (ef38a4d9756) built the GROUP BY ALL list by calling addTargetToGroupList() directly on each target, which uses default sort/group semantics. That bypassed the logic that copies operator information from a matching ORDER BY item, so a query like SELECT a, count(*) FROM t GROUP BY ALL ORDER BY a USING grouped with the type's default equality instead of the equality implied by ORDER BY, giving different results from the equivalent explicit GROUP BY. Building on the preceding restructuring of transformGroupClause(), GROUP BY ALL no longer has a separate code path. groupByAllTargets() supplies the qualifying target-list entries as the grouping list, and they are then processed exactly like explicitly written items, so ORDER BY semantics, duplicate handling and the GROUP BY () fallback all come from the shared code. Regression tests cover the plan shapes for the various target-list cases, the one-row result for an all-aggregate or empty target list, and that GROUP BY ALL matches an explicit GROUP BY under ORDER BY ... USING with non-default (record_image) equality, for both sorted and hashed aggregation, including after view deparse and reload. catversion bump due to the new Query.groupByAll field. Discussion: https://postgr.es/m/DMGKNP0U6UU0.2OJCFUQ2T4FFC@gmail.com --- doc/src/sgml/queries.sgml | 29 +++ doc/src/sgml/ref/select.sgml | 15 +- doc/src/sgml/ref/select_into.sgml | 2 +- src/backend/parser/analyze.c | 2 + src/backend/parser/gram.y | 15 ++ src/backend/parser/parse_clause.c | 72 +++++- src/backend/utils/adt/ruleutils.c | 4 +- src/include/catalog/catversion.h | 2 +- src/include/nodes/parsenodes.h | 2 + src/include/parser/parse_clause.h | 1 + src/test/regress/expected/aggregates.out | 265 +++++++++++++++++++++++ src/test/regress/sql/aggregates.sql | 114 ++++++++++ 12 files changed, 517 insertions(+), 6 deletions(-) diff --git a/doc/src/sgml/queries.sgml b/doc/src/sgml/queries.sgml index eadec64167..c3d7606386 100644 --- a/doc/src/sgml/queries.sgml +++ b/doc/src/sgml/queries.sgml @@ -1154,6 +1154,35 @@ SELECT product_id, p.name, (sum(s.units) * p.price) AS sales expressions cannot contain aggregate functions or window functions). + + PostgreSQL also supports the syntax + GROUP BY ALL, which is equivalent to explicitly + writing all select-list entries that do not contain either an aggregate + function referring to the same query level or a window function. This + can greatly simplify ad-hoc exploration of data. If every select-list + entry contains an aggregate or window function (or the select list is + empty), GROUP BY ALL behaves like + GROUP BY (), so one row is returned even if the input + is empty. As an example, these queries are equivalent: + +=> SELECT a, b, a + b, sum(c) FROM test1 GROUP BY ALL; + a | b | ?column? | sum +---+---+----------+---- + 1 | 4 | 5 | 9 + 2 | 5 | 7 | 12 + 3 | 6 | 9 | 15 +(3 rows) + +=> SELECT a, b, a + b, sum(c) FROM test1 GROUP BY a, b, a + b; + a | b | ?column? | sum +---+---+----------+---- + 1 | 4 | 5 | 9 + 2 | 5 | 7 | 12 + 3 | 6 | 9 | 15 +(3 rows) + + + HAVING diff --git a/doc/src/sgml/ref/select.sgml b/doc/src/sgml/ref/select.sgml index 18392f7cae..a83c0887ff 100644 --- a/doc/src/sgml/ref/select.sgml +++ b/doc/src/sgml/ref/select.sgml @@ -37,7 +37,7 @@ SELECT [ ALL | DISTINCT [ ON ( expressionexpression [ [ AS ] output_name ] } [, ...] ] [ FROM from_item [, ...] ] [ WHERE condition ] - [ GROUP BY [ ALL | DISTINCT ] grouping_element [, ...] ] + [ GROUP BY { ALL | [ ALL | DISTINCT ] grouping_element [, ...] } ] [ HAVING condition ] [ WINDOW window_name AS ( window_definition ) [, ...] ] [ { UNION | INTERSECT | EXCEPT } [ ALL | DISTINCT ] select ] @@ -796,7 +796,7 @@ WHERE condition The optional GROUP BY clause has the general form -GROUP BY [ ALL | DISTINCT ] grouping_element [, ...] +GROUP BY { ALL | [ ALL | DISTINCT ] grouping_element [, ...] } @@ -814,6 +814,17 @@ GROUP BY [ ALL | DISTINCT ] grouping_element + + The form GROUP BY ALL with no explicit + grouping_elements + provided is equivalent to writing GROUP BY with the + numbers of all SELECT output columns that do not + contain either an aggregate function referring to the same query level or + a window function. If no output columns qualify, the effect is the same + as GROUP BY (), so one row is returned even if the + input is empty. + + If any of GROUPING SETS, ROLLUP or CUBE are present as grouping elements, then the diff --git a/doc/src/sgml/ref/select_into.sgml b/doc/src/sgml/ref/select_into.sgml index 550ba69d5d..cbf865ff83 100644 --- a/doc/src/sgml/ref/select_into.sgml +++ b/doc/src/sgml/ref/select_into.sgml @@ -27,7 +27,7 @@ SELECT [ ALL | DISTINCT [ ON ( expressionnew_table [ FROM from_item [, ...] ] [ WHERE condition ] - [ GROUP BY [ ALL | DISTINCT ] grouping_element [, ...] ] + [ GROUP BY { ALL | [ ALL | DISTINCT ] grouping_element [, ...] } ] [ HAVING condition ] [ WINDOW window_name AS ( window_definition ) [, ...] ] [ { UNION | INTERSECT | EXCEPT } [ ALL | DISTINCT ] select ] diff --git a/src/backend/parser/analyze.c b/src/backend/parser/analyze.c index c980d65c74..3e8288d735 100644 --- a/src/backend/parser/analyze.c +++ b/src/backend/parser/analyze.c @@ -1496,12 +1496,14 @@ transformSelectStmt(ParseState *pstate, SelectStmt *stmt, qry->groupClause = transformGroupClause(pstate, stmt->groupClause, + stmt->groupByAll, &qry->groupingSets, &qry->targetList, qry->sortClause, EXPR_KIND_GROUP_BY, false /* allow SQL92 rules */ ); qry->groupDistinct = stmt->groupDistinct; + qry->groupByAll = stmt->groupByAll; if (stmt->distinctClause == NIL) { diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y index 0563453fe2..9536ab0624 100644 --- a/src/backend/parser/gram.y +++ b/src/backend/parser/gram.y @@ -120,6 +120,7 @@ typedef struct SelectLimit typedef struct GroupClause { bool distinct; + bool all; List *list; } GroupClause; @@ -13221,6 +13222,7 @@ simple_select: n->whereClause = $6; n->groupClause = ($7)->list; n->groupDistinct = ($7)->distinct; + n->groupByAll = ($7)->all; n->havingClause = $8; n->windowClause = $9; $$ = (Node *) n; @@ -13238,6 +13240,7 @@ simple_select: n->whereClause = $6; n->groupClause = ($7)->list; n->groupDistinct = ($7)->distinct; + n->groupByAll = ($7)->all; n->havingClause = $8; n->windowClause = $9; $$ = (Node *) n; @@ -13735,14 +13738,25 @@ group_clause: GroupClause *n = palloc_object(GroupClause); n->distinct = $3 == SET_QUANTIFIER_DISTINCT; + n->all = false; n->list = $4; $$ = n; } + | GROUP_P BY ALL + { + GroupClause *n = palloc_object(GroupClause); + + n->distinct = false; + n->all = true; + n->list = NIL; + $$ = n; + } | /*EMPTY*/ { GroupClause *n = palloc_object(GroupClause); n->distinct = false; + n->all = false; n->list = NIL; $$ = n; } @@ -17957,6 +17971,7 @@ PLpgSQL_Expr: opt_distinct_clause opt_target_list n->whereClause = $4; n->groupClause = ($5)->list; n->groupDistinct = ($5)->distinct; + n->groupByAll = ($5)->all; n->havingClause = $6; n->windowClause = $7; n->sortClause = $8; diff --git a/src/backend/parser/parse_clause.c b/src/backend/parser/parse_clause.c index bba1f9bc3e..ac164ae6a8 100644 --- a/src/backend/parser/parse_clause.c +++ b/src/backend/parser/parse_clause.c @@ -2370,10 +2370,16 @@ typedef struct GroupClauseState * grouping item differ (SQL92 additionally allows output-column names and * numbers). If the expression is not already in the targetlist, it is added * as a resjunk entry. + * + * Items supplied by GROUP BY ALL are already targetlist entries (see + * groupByAllTargets), so they need no lookup. */ static TargetEntry * resolveGroupingExpr(GroupClauseState *gcs, Node *gexpr) { + if (IsA(gexpr, TargetEntry)) + return (TargetEntry *) gexpr; + if (gcs->useSQL99) return findTargetlistEntrySQL99(gcs->pstate, gexpr, gcs->targetlist, gcs->exprKind); @@ -2555,6 +2561,57 @@ transformGroupingSet(GroupClauseState *gcs, GroupingSet *gset, bool toplevel) return (Node *) makeGroupingSet(gset->kind, content, gset->location); } +/* + * Build the implicit grouping list for GROUP BY ALL. + * + * GROUP BY ALL groups by every non-junk targetlist entry that does not + * contain an aggregate of the current query level or a window function. + * The entries themselves are returned as the grouping items, so they go + * through exactly the same code path as an explicitly written GROUP BY list; + * in particular, an entry that also appears in ORDER BY inherits that item's + * equality and ordering semantics, just as it would if spelled out. + * + * If no entry qualifies, the SQL standard says to treat the clause as + * "GROUP BY ()", so return an empty grouping set in that case. This means + * one row is returned even if the input is empty. + */ +static List * +groupByAllTargets(ParseState *pstate, List *targetlist) +{ + List *result = NIL; + + foreach_node(TargetEntry, tle, targetlist) + { + /* Ignore junk TLEs */ + if (tle->resjunk) + continue; + + /* + * TLEs containing aggregates are not okay to add to GROUP BY (compare + * checkTargetlistEntrySQL92). But the SQL standard directs us to + * skip them, so it's fine. + */ + if (pstate->p_hasAggs && + contain_aggs_of_level((Node *) tle->expr, 0)) + continue; + + /* + * Likewise, TLEs containing window functions are not okay to add to + * GROUP BY, and the SQL standard directs us to skip them. + */ + if (pstate->p_hasWindowFuncs && + contain_windowfuncs((Node *) tle->expr)) + continue; + + result = lappend(result, tle); + } + + if (result == NIL) + result = list_make1(makeGroupingSet(GROUPING_SET_EMPTY, NIL, -1)); + + return result; +} + /* * transformGroupClause - @@ -2591,10 +2648,14 @@ transformGroupingSet(GroupClauseState *gcs, GroupingSet *gset, bool toplevel) * aggregates or a HAVING clause with no GROUP BY; the output is one row per * grouping set even if the input is empty. * + * If GROUP BY ALL is specified, the grouping list is inferred from the + * targetlist by groupByAllTargets() and then processed like any other. + * * Returns the transformed (flat) groupClause. * * pstate ParseState * grouplist clause to transform + * groupByAll is this a GROUP BY ALL statement? * groupingSets reference to list to contain the grouping set tree * targetlist reference to TargetEntry list * sortClause ORDER BY clause (SortGroupClause nodes) @@ -2602,7 +2663,8 @@ transformGroupingSet(GroupClauseState *gcs, GroupingSet *gset, bool toplevel) * useSQL99 SQL99 rather than SQL92 syntax */ List * -transformGroupClause(ParseState *pstate, List *grouplist, List **groupingSets, +transformGroupClause(ParseState *pstate, List *grouplist, bool groupByAll, + List **groupingSets, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99) { @@ -2619,6 +2681,13 @@ transformGroupClause(ParseState *pstate, List *grouplist, List **groupingSets, gcs.useSQL99 = useSQL99; gcs.flatresult = NIL; + if (groupByAll) + { + /* There cannot have been any explicit grouplist items */ + Assert(grouplist == NIL); + grouplist = groupByAllTargets(pstate, *targetlist); + } + /* * Recursively flatten implicit RowExprs. (Technically this is only needed * for GROUP BY, per the syntax rules for grouping sets, but we do it @@ -2786,6 +2855,7 @@ transformWindowDefinitions(ParseState *pstate, true /* force SQL99 rules */ ); partitionClause = transformGroupClause(pstate, windef->partitionClause, + false /* not GROUP BY ALL */ , NULL, targetlist, orderClause, diff --git a/src/backend/utils/adt/ruleutils.c b/src/backend/utils/adt/ruleutils.c index b2d5327cc2..f97ab5bd6f 100644 --- a/src/backend/utils/adt/ruleutils.c +++ b/src/backend/utils/adt/ruleutils.c @@ -6212,7 +6212,9 @@ get_basic_select_query(Query *query, deparse_context *context) save_ingroupby = context->inGroupBy; context->inGroupBy = true; - if (query->groupingSets == NIL) + if (query->groupByAll) + appendStringInfoString(buf, "ALL"); + else if (query->groupingSets == NIL) { sep = ""; foreach(l, query->groupClause) diff --git a/src/include/catalog/catversion.h b/src/include/catalog/catversion.h index f58fcc2819..edd300bf68 100644 --- a/src/include/catalog/catversion.h +++ b/src/include/catalog/catversion.h @@ -57,6 +57,6 @@ */ /* yyyymmddN */ -#define CATALOG_VERSION_NO 202611241 +#define CATALOG_VERSION_NO 202611291 #endif diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h index 5be1d4a944..12cdf0c27a 100644 --- a/src/include/nodes/parsenodes.h +++ b/src/include/nodes/parsenodes.h @@ -217,6 +217,7 @@ typedef struct Query List *groupClause; /* a list of SortGroupClause's */ bool groupDistinct; /* was GROUP BY DISTINCT used? */ + bool groupByAll; /* was GROUP BY ALL used? */ List *groupingSets; /* a list of GroupingSet's if present */ @@ -2241,6 +2242,7 @@ typedef struct SelectStmt Node *whereClause; /* WHERE qualification */ List *groupClause; /* GROUP BY clauses */ bool groupDistinct; /* Is this GROUP BY DISTINCT? */ + bool groupByAll; /* Is this GROUP BY ALL? */ Node *havingClause; /* HAVING conditional-expression */ List *windowClause; /* WINDOW window_name AS (...), ... */ diff --git a/src/include/parser/parse_clause.h b/src/include/parser/parse_clause.h index ca815a9d1b..fe23461100 100644 --- a/src/include/parser/parse_clause.h +++ b/src/include/parser/parse_clause.h @@ -26,6 +26,7 @@ extern Node *transformLimitClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName, LimitOption limitOption); extern List *transformGroupClause(ParseState *pstate, List *grouplist, + bool groupByAll, List **groupingSets, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99); diff --git a/src/test/regress/expected/aggregates.out b/src/test/regress/expected/aggregates.out index 275263c293..f59eac888f 100644 --- a/src/test/regress/expected/aggregates.out +++ b/src/test/regress/expected/aggregates.out @@ -1809,6 +1809,140 @@ NOTICE: drop cascades to table t1c drop table t2; drop table t3; drop table p_t1; +-- +-- Test GROUP BY ALL +-- +-- We don't care about the data here, just the proper transformation of the +-- GROUP BY clause, so test some queries and verify the EXPLAIN plans. +-- +CREATE TEMP TABLE t1 ( + a int, + b int, + c int +); +-- basic example +EXPLAIN (COSTS OFF) SELECT b, COUNT(*) FROM t1 GROUP BY ALL; + QUERY PLAN +---------------------- + HashAggregate + Group Key: b + -> Seq Scan on t1 +(3 rows) + +-- multiple columns, non-consecutive order +EXPLAIN (COSTS OFF) SELECT a, SUM(b), b FROM t1 GROUP BY ALL; + QUERY PLAN +---------------------- + HashAggregate + Group Key: a, b + -> Seq Scan on t1 +(3 rows) + +-- multi columns, no aggregate +EXPLAIN (COSTS OFF) SELECT a + b FROM t1 GROUP BY ALL; + QUERY PLAN +---------------------- + HashAggregate + Group Key: (a + b) + -> Seq Scan on t1 +(3 rows) + +-- check we detect a non-top-level aggregate +EXPLAIN (COSTS OFF) SELECT a, SUM(b) + 4 FROM t1 GROUP BY ALL; + QUERY PLAN +---------------------- + HashAggregate + Group Key: a + -> Seq Scan on t1 +(3 rows) + +-- including grouped column is okay +EXPLAIN (COSTS OFF) SELECT a, SUM(b) + a FROM t1 GROUP BY ALL; + QUERY PLAN +---------------------- + HashAggregate + Group Key: a + -> Seq Scan on t1 +(3 rows) + +-- including non-grouped column, not so much +EXPLAIN (COSTS OFF) SELECT a, SUM(b) + c FROM t1 GROUP BY ALL; +ERROR: column "t1.c" must appear in the GROUP BY clause or be used in an aggregate function +LINE 1: EXPLAIN (COSTS OFF) SELECT a, SUM(b) + c FROM t1 GROUP BY AL... + ^ +-- all aggregates, should reduce to GROUP BY () +EXPLAIN (COSTS OFF) SELECT COUNT(a), SUM(b) FROM t1 GROUP BY ALL; + QUERY PLAN +---------------------- + Aggregate + Group Key: () + -> Seq Scan on t1 +(3 rows) + +-- likewise with empty target list +EXPLAIN (COSTS OFF) SELECT FROM t1 GROUP BY ALL; + QUERY PLAN +----------------------- + Result + Replaces: Aggregate +(2 rows) + +-- like GROUP BY (), these return one row even though t1 is empty +SELECT COUNT(a), SUM(b) FROM t1 GROUP BY ALL; + count | sum +-------+----- + 0 | +(1 row) + +SELECT FROM t1 GROUP BY ALL; +-- +(1 row) + +-- window functions are not to be included in GROUP BY, either +EXPLAIN (COSTS OFF) SELECT a, COUNT(a) OVER (PARTITION BY a) FROM t1 GROUP BY ALL; + QUERY PLAN +---------------------------------- + WindowAgg + Window: w1 AS (PARTITION BY a) + -> Sort + Sort Key: a + -> HashAggregate + Group Key: a + -> Seq Scan on t1 +(7 rows) + +-- all cols +EXPLAIN (COSTS OFF) SELECT *, count(*) FROM t1 GROUP BY ALL; + QUERY PLAN +---------------------- + HashAggregate + Group Key: a, b, c + -> Seq Scan on t1 +(3 rows) + +-- group by all with grouping element(s) (equivalent to GROUP BY's +-- default behavior, explicit antithesis to GROUP BY DISTINCT) +EXPLAIN (COSTS OFF) SELECT a, count(*) FROM t1 GROUP BY ALL a; + QUERY PLAN +---------------------- + HashAggregate + Group Key: a + -> Seq Scan on t1 +(3 rows) + +-- verify deparsing of GROUP BY ALL +CREATE TEMP VIEW v1 AS SELECT b, COUNT(*) FROM t1 GROUP BY ALL; +SELECT pg_get_viewdef('v1'::regclass); + pg_get_viewdef +----------------------- + SELECT b, + + count(*) AS count+ + FROM t1 + + GROUP BY ALL; +(1 row) + +DROP VIEW v1; +DROP TABLE t1; -- A composite type used by the tests below to exercise the asymmetry -- between record_ops (per-field equality, the default) and record_image_ops -- (bytewise equality): values like row(1.0) and row(1.00) are field-equal @@ -1901,6 +2035,137 @@ select a, count(*) from t_having group by a having a = row(1.0)::avg_rec; (1 row) drop table t_having; +-- GROUP BY ALL must inherit equality semantics from a matching ORDER BY item, +-- exactly as an explicitly-spelled-out GROUP BY does. Using record_image_ops +-- (bytewise equality) via ORDER BY ... USING, the byte-distinct values +-- row(1.0) and row(1.00) must form two groups, not one. record_image_ops has +-- no hash support, so this is always a sorted aggregate. +create temp table t_gba (a avg_rec); +insert into t_gba values (row(1.0)::avg_rec), (row(1.00)::avg_rec); +set enable_hashagg = off; +-- explicit GROUP BY: two groups (record_image inequality from ORDER BY) +select a, count(*) from t_gba + group by a order by a using operator(pg_catalog.*<); + a | count +--------+------- + (1.00) | 1 + (1.0) | 1 +(2 rows) + +-- GROUP BY ALL: must match the explicit form (two groups) +explain (costs off) +select a, count(*) from t_gba + group by all order by a using operator(pg_catalog.*<); + QUERY PLAN +------------------------------- + GroupAggregate + Group Key: a + -> Sort + Sort Key: a USING *< + -> Seq Scan on t_gba +(5 rows) + +select a, count(*) from t_gba + group by all order by a using operator(pg_catalog.*<); + a | count +--------+------- + (1.00) | 1 + (1.0) | 1 +(2 rows) + +reset enable_hashagg; +-- with hashed aggregation enabled and preferred, the planner must still +-- sort, since the inherited record_image equality is not hashable; the +-- result must again match the explicit GROUP BY +set enable_sort = off; +explain (costs off) +select a, count(*) from t_gba + group by all order by a using operator(pg_catalog.*<); + QUERY PLAN +------------------------------- + GroupAggregate + Group Key: a + -> Sort + Disabled: true + Sort Key: a USING *< + -> Seq Scan on t_gba +(6 rows) + +select a, count(*) from t_gba + group by all order by a using operator(pg_catalog.*<); + a | count +--------+------- + (1.00) | 1 + (1.0) | 1 +(2 rows) + +reset enable_sort; +-- for default (hashable) equality, hashed and sorted GROUP BY ALL agree +set enable_hashagg = off; +explain (costs off) +select a, count(*) from t_gba group by all; + QUERY PLAN +------------------------------- + GroupAggregate + Group Key: a + -> Sort + Sort Key: a + -> Seq Scan on t_gba +(5 rows) + +select a, count(*) from t_gba group by all order by a; + a | count +-------+------- + (1.0) | 2 +(1 row) + +reset enable_hashagg; +set enable_sort = off; +explain (costs off) +select a, count(*) from t_gba group by all; + QUERY PLAN +------------------------- + HashAggregate + Group Key: a + -> Seq Scan on t_gba +(3 rows) + +select a, count(*) from t_gba group by all order by a; + a | count +-------+------- + (1.0) | 2 +(1 row) + +reset enable_sort; +-- without the record_image ORDER BY, default record_ops merges them (one group) +select a, count(*) from t_gba group by all order by a; + a | count +-------+------- + (1.0) | 2 +(1 row) + +-- the ORDER BY ... USING semantics must survive view deparse and reload +create temp view v_gba as + select a, count(*) from t_gba group by all order by a using operator(pg_catalog.*<); +select pg_get_viewdef('v_gba'::regclass); + pg_get_viewdef +----------------------------------- + SELECT a, + + count(*) AS count + + FROM t_gba + + GROUP BY ALL + + ORDER BY a USING *< NULLS LAST; +(1 row) + +select * from v_gba; + a | count +--------+------- + (1.00) | 1 + (1.0) | 1 +(2 rows) + +drop view v_gba; +drop table t_gba; drop type avg_rec; -- -- Test GROUP BY matching of join columns that are type-coerced due to USING diff --git a/src/test/regress/sql/aggregates.sql b/src/test/regress/sql/aggregates.sql index 2bbb7668dd..f917f72414 100644 --- a/src/test/regress/sql/aggregates.sql +++ b/src/test/regress/sql/aggregates.sql @@ -644,6 +644,64 @@ drop table t2; drop table t3; drop table p_t1; +-- +-- Test GROUP BY ALL +-- +-- We don't care about the data here, just the proper transformation of the +-- GROUP BY clause, so test some queries and verify the EXPLAIN plans. +-- + +CREATE TEMP TABLE t1 ( + a int, + b int, + c int +); + +-- basic example +EXPLAIN (COSTS OFF) SELECT b, COUNT(*) FROM t1 GROUP BY ALL; + +-- multiple columns, non-consecutive order +EXPLAIN (COSTS OFF) SELECT a, SUM(b), b FROM t1 GROUP BY ALL; + +-- multi columns, no aggregate +EXPLAIN (COSTS OFF) SELECT a + b FROM t1 GROUP BY ALL; + +-- check we detect a non-top-level aggregate +EXPLAIN (COSTS OFF) SELECT a, SUM(b) + 4 FROM t1 GROUP BY ALL; + +-- including grouped column is okay +EXPLAIN (COSTS OFF) SELECT a, SUM(b) + a FROM t1 GROUP BY ALL; + +-- including non-grouped column, not so much +EXPLAIN (COSTS OFF) SELECT a, SUM(b) + c FROM t1 GROUP BY ALL; + +-- all aggregates, should reduce to GROUP BY () +EXPLAIN (COSTS OFF) SELECT COUNT(a), SUM(b) FROM t1 GROUP BY ALL; + +-- likewise with empty target list +EXPLAIN (COSTS OFF) SELECT FROM t1 GROUP BY ALL; + +-- like GROUP BY (), these return one row even though t1 is empty +SELECT COUNT(a), SUM(b) FROM t1 GROUP BY ALL; +SELECT FROM t1 GROUP BY ALL; + +-- window functions are not to be included in GROUP BY, either +EXPLAIN (COSTS OFF) SELECT a, COUNT(a) OVER (PARTITION BY a) FROM t1 GROUP BY ALL; + +-- all cols +EXPLAIN (COSTS OFF) SELECT *, count(*) FROM t1 GROUP BY ALL; + +-- group by all with grouping element(s) (equivalent to GROUP BY's +-- default behavior, explicit antithesis to GROUP BY DISTINCT) +EXPLAIN (COSTS OFF) SELECT a, count(*) FROM t1 GROUP BY ALL a; + +-- verify deparsing of GROUP BY ALL +CREATE TEMP VIEW v1 AS SELECT b, COUNT(*) FROM t1 GROUP BY ALL; +SELECT pg_get_viewdef('v1'::regclass); + +DROP VIEW v1; +DROP TABLE t1; + -- A composite type used by the tests below to exercise the asymmetry -- between record_ops (per-field equality, the default) and record_image_ops -- (bytewise equality): values like row(1.0) and row(1.00) are field-equal @@ -689,6 +747,62 @@ select a, count(*) from t_having group by a having a = row(1.0)::avg_rec; select a, count(*) from t_having group by a having a = row(1.0)::avg_rec; drop table t_having; + +-- GROUP BY ALL must inherit equality semantics from a matching ORDER BY item, +-- exactly as an explicitly-spelled-out GROUP BY does. Using record_image_ops +-- (bytewise equality) via ORDER BY ... USING, the byte-distinct values +-- row(1.0) and row(1.00) must form two groups, not one. record_image_ops has +-- no hash support, so this is always a sorted aggregate. +create temp table t_gba (a avg_rec); +insert into t_gba values (row(1.0)::avg_rec), (row(1.00)::avg_rec); + +set enable_hashagg = off; +-- explicit GROUP BY: two groups (record_image inequality from ORDER BY) +select a, count(*) from t_gba + group by a order by a using operator(pg_catalog.*<); +-- GROUP BY ALL: must match the explicit form (two groups) +explain (costs off) +select a, count(*) from t_gba + group by all order by a using operator(pg_catalog.*<); +select a, count(*) from t_gba + group by all order by a using operator(pg_catalog.*<); + +reset enable_hashagg; + +-- with hashed aggregation enabled and preferred, the planner must still +-- sort, since the inherited record_image equality is not hashable; the +-- result must again match the explicit GROUP BY +set enable_sort = off; +explain (costs off) +select a, count(*) from t_gba + group by all order by a using operator(pg_catalog.*<); +select a, count(*) from t_gba + group by all order by a using operator(pg_catalog.*<); +reset enable_sort; + +-- for default (hashable) equality, hashed and sorted GROUP BY ALL agree +set enable_hashagg = off; +explain (costs off) +select a, count(*) from t_gba group by all; +select a, count(*) from t_gba group by all order by a; +reset enable_hashagg; +set enable_sort = off; +explain (costs off) +select a, count(*) from t_gba group by all; +select a, count(*) from t_gba group by all order by a; +reset enable_sort; + +-- without the record_image ORDER BY, default record_ops merges them (one group) +select a, count(*) from t_gba group by all order by a; + +-- the ORDER BY ... USING semantics must survive view deparse and reload +create temp view v_gba as + select a, count(*) from t_gba group by all order by a using operator(pg_catalog.*<); +select pg_get_viewdef('v_gba'::regclass); +select * from v_gba; +drop view v_gba; +drop table t_gba; + drop type avg_rec; -- -- 2.56.0