BUG #19873: planner silently drops the second ORDER BY sort key when both keys reference the same expression und
Thread notes
1 note#bug
hackorum-bot#bug
@global #bug
The following bug has been logged on the website:
Bug reference: 19873
Logged by: chunling qin
Email address: 303677365@qq.com
PostgreSQL version: 18.6
Operating system: Linux x86_64 (official Docker image); platform-ind
Description:
**Description:**
`ORDER BY x USING <, x USING ~<~` — two sort keys on the *same* expression,
using different btree operator families (the default `text_ops` `<` and the
bytewise `text_pattern_ops` `~<~`). Under a *nondeterministic* collation the
first key has ties (`'a' = 'A'`), and the second key is exactly what the
user asked for to break those ties bytewise. The planner collapses both keys
into one EquivalenceClass and discards the second as redundant, so the
result comes out in the wrong order — and `DISTINCT ON`, `min/max(... ORDER
BY ...)` and aggregates with `ORDER BY` pick different
representatives/arrays depending on which plan is chosen.
**Reproduction (self-contained SQL; verified verbatim on 18.6 and master):**
```sql
DROP TABLE IF EXISTS t, t2 CASCADE;
DROP COLLATION IF EXISTS ci CASCADE;
CREATE COLLATION ci (provider = icu, locale = 'und-u-ks-level2',
deterministic = false);
CREATE TABLE t (x text COLLATE ci);
-- interleaved case variants: under ci 'a'='A' (tie under <), but 'A' < 'a'
bytewise
INSERT INTO t VALUES ('a'),('A'),('a'),('A'),('b'),('B'),('b'),('B');
-- operator semantics: ci is case-insensitive; ~<~ is bytewise
SELECT 'a' = 'A' COLLATE ci AS ci_eq, -- t
'a' < 'A' COLLATE ci AS ci_lt, -- f (tie)
'A' ~<~ 'a' COLLATE ci AS bytewise; -- t (the tie-break)
-- CONTROL: the bytewise tie-break the user asked for, as a single-key
query:
SELECT array_agg(x ORDER BY x USING ~<~) AS bytewise_only FROM t;
-- {A,A,B,B,a,a,b,b} <- the correct tie-broken order
-- CONTROL 2: second key with a DIFFERENT collation -> different EC -> both
keys honored
-- (on master this returns the tie-broken order {A,A,a,a,B,B,b,b};
-- on the 18.6 image tested this control is collapsed to the first key too,
-- i.e. the drop-key face is even wider there):
SELECT array_agg(x ORDER BY x USING <, x COLLATE "C" USING <) AS
control_both_keys FROM t;
-- SUSPECT: second key with a different opfamily on the SAME expression ->
dropped:
SELECT array_agg(x)::text COLLATE "C" AS plain_2keys
FROM (SELECT x FROM t ORDER BY x USING <, x USING ~<~) s;
-- {a,A,a,A,b,B,b,B} <- wrong: only the first key was honored
EXPLAIN (COSTS OFF) SELECT x FROM t ORDER BY x USING <, x USING ~<~;
-- Sort
-- Sort Key: x COLLATE ci <- the second key is simply gone
-- CONTROL for the whole report: deterministic collation -> the second key
is
-- genuinely redundant there, and both plans agree (no divergence):
CREATE TABLE t2 (x text COLLATE "C");
INSERT INTO t2 VALUES ('a'),('A'),('a'),('A'),('b'),('B'),('b'),('B');
SELECT array_agg(x ORDER BY x USING <, x USING ~<~) AS det_control FROM t2;
```
**Additional face observed on a current master build (20devel,
2026-11-09):** ordered aggregates with the same two keys diverge across a
pure planner GUC —
```sql
SET enable_presorted_aggregate = off;
SELECT min(x ORDER BY x USING <, x USING ~<~) AS min_off,
max(x ORDER BY x USING <, x USING ~<~) AS max_off FROM t;
SET enable_presorted_aggregate = on;
SELECT min(x ORDER BY x USING <, x USING ~<~) AS min_on,
max(x ORDER BY x USING <, x USING ~<~) AS max_on FROM t;
-- observed: off returns (min=a, max=b); on returns (min=A, max=B);
-- the correct two-key answer is (min=A, max=b) — the bytewise tie-break
-- picks 'A' first in the a-group and 'b' last in the b-group.
-- So the two plans disagree with each other AND each is wrong.
```
(Do not run this GUC part on a 18.6 build older than 2026-11-04: its `off`
path reaches the executor Datum-sort bug fixed by 91e9e89dc on that date,
which can crash the backend; 18.6 packages updated after 2026-11-04 are
fine.)
**Actual results:** under the nondeterministic collation the second ORDER BY
key is ignored; `EXPLAIN` shows a single Sort Key. The output order and the
representatives chosen by `DISTINCT ON` / ordered aggregates depend on which
plan happens to be picked (an optimization choice), which is the definition
of a wrong result.
**Expected behavior:** two sort keys that use different operator families
(different btree opclasses) must not be treated as redundant: under a
nondeterministic collation the first key can tie, and only the second key
decides the order. The equivalence-class machinery must not merge keys whose
operator families differ (or must at least keep the second key when the
first key's equality is not the identity).
**Related, but distinct:** the recent executor-side fixes "Fix accidental
ignoring of subsequent keys in Sort nodes" (91e9e89dc and master
edbe7ffdc8a, from the thread "Wrong result: count(DISTINCT x COLLATE "C")
with GROUP BY x on a nondeterministic collation") address the *executor*
Datum-sort path when a plan already carries both keys. This report is the
*planner* side: the second key never reaches the plan at all, so those fixes
cannot help.
**Impact:** wrong results for plain `ORDER BY`, `DISTINCT ON`, ordered set
aggregates (`min/max/array_agg/string_agg ... ORDER BY`); on master, results
also flip depending on `enable_presorted_aggregate`.
Thanks for the report, BUG #19869 is the same one. I think it is a
real bug.
A btree opfamily needs its "=" to agree with its ordering. The
pattern_ops opfamilies sort bytewise, but their "=" follows the
collation. With a nondeterministic collation, 'A' ~<~ 'a' and
'A' = 'a' are both true. Anything that sorts and then tests for
equality goes wrong. With your table t, this returns 4 and the right
answer is 8:
CREATE TABLE t2 (y text COLLATE ci);
INSERT INTO t2 VALUES ('a'), ('B');
SET enable_hashjoin = off; SET enable_nestloop = off;
SELECT count(*) FROM (SELECT x FROM t JOIN t2 ON x = y
ORDER BY x USING ~<~) s;
GROUP BY and DISTINCT break the same way.
Commit 2810396312 kept a check for this only in CREATE INDEX. The
attached patch adds the same check to ORDER BY. Its hint points to
COLLATE "C", which sorts the same way. Both checks now use one small
function for the list of opfamilies. The partition key patch in [1]/messages/by-id/19645-60a963f2e91478e0@postgresql.org
could use it too.
Such queries mostly work today and views using them would no longer
restore, so I'd suggest HEAD only.
[1]: /messages/by-id/19645-60a963f2e91478e0@postgresql.org
Thanks,
Shihao
Attachments:
t258478_2v1-0002-Add-tests-for-pattern_ops-operators-with-nondetermin.patchapplication/octet-stream; name=v1-0002-Add-tests-for-pattern_ops-operators-with-nondetermin.patchDownload+67-1
nocfbot-v1-REL_15.patchapplication/octet-stream; name=nocfbot-v1-REL_15.patchDownload+160-7
v1-0001-Reject-pattern_ops-ordering-operators-for-nondetermi.patchapplication/octet-stream; name=v1-0001-Reject-pattern_ops-ordering-operators-for-nondetermi.patchDownload+92-6
nocfbot-v1-REL_18.patchapplication/octet-stream; name=nocfbot-v1-REL_18.patchDownload+159-7
shihao zhong <zhong950419@gmail.com> writes:
Thanks for the report, BUG #19869 is the same one. I think it is a
real bug.
I agree it's a bug, but your patch is solving a different problem.
Specifically, this patch prevents reaching the bug for the specific
case of the btree_pattern_ops operators, but it does nothing for
other operators, for which this type of query might be more sensible.
I concur with the submitter's opinion that what we really ought to
do is not merge pathkeys that have the same expression and different
collations when the earlier one has a nondeterministic collation.
Not sure how hard it is to make that happen, but that seems like the
Right Thing. The idea that we could merge such cases is founded
precisely on the assumption that the earlier sort column will only
report equality for bitwise-equal strings, so it's one of the
assumptions that nondeterministic collations break.
I'm also not convinced that we need to or should block use of ~<~ in
ORDER BY etc with a nondeterministic collation. AFAICS, specifying
that results in a C-locale sort regardless of the specified collation
for the target expression, and that's fine. The inconsistency in the
btree_pattern_ops opclass doesn't affect using it for sorting, because
at no point will a sort operation invoke the opclass's "=" member.
We blocked this for indexes because you'd get the wrong answers from
an "=" indexscan, but I don't see that there's a hazard for ORDER BY.
(Even if I thought we needed to block this, I'm not very happy
about the number of usually-useless catalog lookups that this
patch adds to parsing ORDER BY etc. But I question the need
to block it at all.)
regards, tom lane
Hi Tom,
Thanks, v2 does it in the planner. Under a nondeterministic collation
a sort key with a non-default opfamily now gets its own
EquivalenceClass, so it is never merged with other keys or clauses.
I also found that GROUP BY x ORDER BY x USING ~<~ is wrong with a
sorted GroupAggregate. It returns 4 groups on the report's table, and
HashAggregate returns 2. Should we fix that in this thread too?
Thank,
Shihao
shihao zhong <zhong950419@gmail.com> writes:
Thanks, v2 does it in the planner. Under a nondeterministic collation
a sort key with a non-default opfamily now gets its own
EquivalenceClass, so it is never merged with other keys or clauses.
Hmm, why should it matter whether the opfamily is default or not?
I grant that the pattern_ops opfamily is collation-insensitive,
but we shouldn't assume that that's universally true.
I also found that GROUP BY x ORDER BY x USING ~<~ is wrong with a
sorted GroupAggregate. It returns 4 groups on the report's table, and
HashAggregate returns 2. Should we fix that in this thread too?
It's not clear to me whether that's sufficiently closely related to be
considered the same bug. Do you have an idea where it needs to be
fixed?
regards, tom lane
Hi Tom,
Hmm, why should it matter whether the opfamily is default or not?
I grant that the pattern_ops opfamily is collation-insensitive,
but we shouldn't assume that that's universally true.
Right. The catalogs can't tell us which opfamilies sort without the
collation while their "=" uses it. index_create() names the pattern_ops
opclasses for that reason, so v3 names their two opfamilies.
I didn't do it your first way, by not merging a key into an earlier
one. That puts one EC twice in a pathkey list and trips two
assertions. It also misses single-key cases like WHERE x = 'a' ORDER
BY x USING ~<~. So v3 gives a pattern_ops sort key its own EC from the
start.
Do you have an idea where it needs to be fixed?
The parser copies ~<~ from ORDER BY into GROUP BY, DISTINCT and
PARTITION BY. Then the grouping sorts by ~<~ but compares with "=".
That is a different mechanism from 0001. So the fix is a separate
v3-0002 in the planner, and you can take 0001 alone. It doesn't fix
DISTINCT ON and aggregate DISTINCT, nor window peers and incremental
sort.
Thanks,
Shihao