| From: | PG Bug reporting form <noreply(at)postgresql(dot)org> |
|---|---|
| To: | pgsql-bugs(at)lists(dot)postgresql(dot)org |
| Cc: | jacobtylerwalls(at)gmail(dot)com |
| Subject: | BUG #19648: Docs on DISTINCT ON do not describe how expressions are matched to ORDER BY |
| Date: | 2026-08-31 23:10:00 |
| Message-ID: | 19648-25e90c26a67ae02e@postgresql.org |
| Views: | Whole Thread | Raw Message | Download mbox | Resend email |
| Thread: | |
| Lists: | pgsql-bugs |
The following bug has been logged on the website:
Bug reference: 19648
Logged by: Jacob Walls
Email address: jacobtylerwalls(at)gmail(dot)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
| From | Date | Subject | |
|---|---|---|---|
| Next Message | Christophe Pettus | 2026-09-01 00:43:00 | Re: REPACK (CONCURRENTLY) doesn't handle invalid indexes |
| Previous Message | Zsolt Parragi | 2026-08-31 23:08:44 | Re: REPACK (CONCURRENTLY) doesn't handle invalid indexes |