DISTINCT aggregate crashes when ORDER BY repeats its argument

From: Ayush Tiwari <ayushtiwari(dot)slg01(at)gmail(dot)com>
To: PostgreSQL Hackers <pgsql-hackers(at)postgresql(dot)org>
Cc: David Rowley <dgrowleyml(at)gmail(dot)com>
Subject: DISTINCT aggregate crashes when ORDER BY repeats its argument
Date: 2026-11-05 17:21:58
Message-ID: CAJTYsWXMuo5QZSy_az+86mty2XdbDw_7uB3C4FjWpFACvD_rzg@mail.gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Hi,

This crashes the backend on master:

CREATE TABLE t (x text);
INSERT INTO t VALUES ('a'), ('a'), ('b');
SELECT array_agg(DISTINCT x ORDER BY x USING ~<~, x USING <)
FROM t;

I could repro it in all supported versions.

IIUC, the parser allows the same argument more than once in ORDER BY
with different sort operators. But we pick the Datum-sort path based
only on the number of inputs, so later sort keys get ignored.

For DISTINCT, we also mix up the number of inputs with the number of
DISTINCT keys..

I noticed this while looking at b715192e52e, which fixes the same
assumption in nodeSort.c. Attached is a patch for the aggregate case,
with tests for both paths. It uses Datum sorting only for one input
and one sort key, and allocates uniqslot for multiple DISTINCT keys.

Thoughts?

Regards,
Ayush

Attachment Content-Type Size
v1-0001-Fix-single-input-aggregates-with-multiple-sort-ke.patch application/octet-stream 6.7 KB

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Raja Sai pranav 2026-11-05 17:55:09 Re: [PATCH] doc: Fix pg_combinebackup's description of --sync-method
Previous Message Álvaro Herrera 2026-11-05 16:59:36 Re: Credits For v19