| From: | David Rowley <drowley(at)postgresql(dot)org> |
|---|---|
| To: | pgsql-committers(at)lists(dot)postgresql(dot)org |
| Subject: | pgsql: Fix accidental ignoring of subsequent keys in Sort nodes |
| Date: | 2026-11-04 21:24:16 |
| Message-ID: | E1xOiSu-00000000DSS-1Zpw@gemulon.postgresql.org |
| Views: | Whole Thread | Raw Message | Download mbox | Resend email |
| Thread: | |
| Lists: | pgsql-committers |
Fix accidental ignoring of subsequent keys in Sort nodes
91e9e89dc (v15) changed nodeSort.c to allow the slightly more efficient
Datum sort method to be used when the Sort node was only outputting a
single column. That commit mistakenly failed to consider additional
sort keys.
This wasn't trivial to hit as adding more sort keys on another column
would add a resjunk target entry, so Datum sort wouldn't be used. Hitting
this required all sort keys to be on the only output column, and then you
might think that subsequent sort keys *could* be ignored in that case, but
the collation for subsequent keys might differ from the first, and if the
first sort key had a nondeterministic collation, ignoring subsequent keys
isn't correct.
Ordinary ORDER BY queries were not affected by this as repeating the same
column in the ORDER BY clause with different collations would lead to
additional redundant target entries and would have failed the one-column
requirement to enable the Datum sort optimization. The only known case
where problems could occur was sorting for the presorted aggregate
optimization added in 1349d2790 (v16).
A query such as the following would trigger this issue if the "x" column
was defined with a nondeterministic collation as the presorted input
would arrive at the aggregate only presorted by 'x' (using its
nondeterministic collation), rather than 'x, x COLLATE "C"':
SELECT count(DISTINCT x COLLATE "C") FROM t GROUP BY x;
This could lead to COUNT(DISTINCT) returning a count higher than the actual
number of distinct values according to the "C" collation.
Fix this by only using the Datum sort optimization when there's 1 output
column and 1 sort key, rather than just checking for 1 output column.
Reported-by: Nidal FAKIH <nidal(dot)fakih(at)soptimal(dot)com>
Author: David Rowley <dgrowleyml(at)gmail(dot)com>
Discussion: https://postgr.es/m/c6790a7b-7c10-4baf-9c8f-b404420c63f9@soptimal.com
Backpatch-through: 15
Branch
------
REL_18_STABLE
Details
-------
https://git.postgresql.org/pg/commitdiff/bfbb3d84209f60698f327ad54176240d27e5ee2a
Modified Files
--------------
src/backend/executor/nodeSort.c | 10 +++++++---
1 file changed, 7 insertions(+), 3 deletions(-)
| From | Date | Subject | |
|---|---|---|---|
| Next Message | David Rowley | 2026-11-04 21:24:33 | pgsql: Fix accidental ignoring of subsequent keys in Sort nodes |
| Previous Message | David Rowley | 2026-11-04 21:24:05 | pgsql: Fix accidental ignoring of subsequent keys in Sort nodes |