pgsql: Fix crash with single-input aggregates with multiple sort keys

From: David Rowley <drowley(at)postgresql(dot)org>
To: pgsql-committers(at)lists(dot)postgresql(dot)org
Subject: pgsql: Fix crash with single-input aggregates with multiple sort keys
Date: 2026-11-06 07:20:11
Message-ID: E1xPEF9-00000000R0O-1YyG@gemulon.postgresql.org
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-committers

Fix crash with single-input aggregates with multiple sort keys

An aggregate's ORDER BY can list the same sort key more than once with
different sort operators, and transformDistinctClause() copies such
items into the DISTINCT list. So an aggregate with a single input can
have several sort keys and several DISTINCT columns.

nodeAgg.c and execExpr.c mistakenly only checked the number of inputs
when deciding if a Datum sort was possible. That check must also
consider the number of sort keys.

Fix by using the Datum sort only for a single input with a single sort
key.

Also for v16+, fix crash in pre-sorted aggregate code where the uniqslot
was only created when the number of inputs for a DISTINCT aggregate was
above 1. The uniqslot is required when there are multiple DISTINCT
columns, and an ORDER BY clause may cause more than one of these to exist
when there's only a single input column.

Author: Ayush Tiwari <ayushtiwari(dot)slg01(at)gmail(dot)com>
Reviewed-by: David Rowley <dgrowleyml(at)gmail(dot)com>
Discussion: https://postgr.es/m/CAJTYsWXMuo5QZSy_az+86mty2XdbDw_7uB3C4FjWpFACvD_rzg@mail.gmail.com
Backpatch-through: 14

Branch
------
REL_19_STABLE

Details
-------
https://git.postgresql.org/pg/commitdiff/1c087e61685c5db80ca898b4c4278bf7a349c602

Modified Files
--------------
src/backend/executor/execExpr.c | 8 ++++----
src/backend/executor/nodeAgg.c | 22 ++++++++++++++--------
src/test/regress/expected/aggregates.out | 28 ++++++++++++++++++++++++++++
src/test/regress/sql/aggregates.sql | 17 +++++++++++++++++
4 files changed, 63 insertions(+), 12 deletions(-)

Browse pgsql-committers by date

  From Date Subject
Next Message David Rowley 2026-11-06 07:20:19 pgsql: Fix crash with single-input aggregates with multiple sort keys
Previous Message David Rowley 2026-11-06 07:19:57 pgsql: Fix crash with single-input aggregates with multiple sort keys