BUG #19648: Docs on DISTINCT ON do not describe how expressions are matched to ORDER BY

Started by PG Bug reporting form9 days ago1 messagesbugs
Jump to latest
#1PG Bug reporting form
noreply@postgresql.org

The following bug has been logged on the website:

Bug reference: 19648
Logged by: Jacob Walls
Email address: jacobtylerwalls@gmail.com
PostgreSQL version: 18.4
Operating system: Linux
Description:

Hi,

The SELECT page states: "The DISTINCT ON expression(s) must match the
leftmost ORDER BY expression(s)."

However, the notion of "matching" is quite specific: it appears to also
matter which alias is used in the ordering, as shown by its position in the
select list:
```
CREATE TABLE t (a int);
SELECT DISTINCT ON (a) a AS x, a AS y FROM t ORDER BY y;
```
Gives:
ERROR: SELECT DISTINCT ON expressions must match initial ORDER BY
expressions

We hit this error in the Django ORM by generating SQL like:
```
CREATE TABLE t (a int, b int);
SELECT DISTINCT ON (a, a, b) a, a, b FROM t ORDER BY a, a, b; -- ok
SELECT DISTINCT ON (a, a, b) a, a, b FROM t ORDER BY 1, 2, 3; -- ERROR
SELECT DISTINCT ON (a) a, a as x FROM t ORDER BY x; -- ERROR
```

As part of fixing this in Django, we'd like to know the rule we should be
coding against. Is it accurate to say that DISTINCT ON expressions are
matched to select-list entries, and that two entries holding the same value
count separately? If so, would it be worth stating anything around this in
the docs?

Thanks,
Jacob