agora inbox for pgsql-bugs@postgresql.org  
help / color / mirror / Atom feed
From: PG Bug reporting form <noreply@postgresql.org>
To: pgsql-bugs@lists.postgresql.org
Cc: jacobtylerwalls@gmail.com
Subject: BUG #19648: Docs on DISTINCT ON do not describe how expressions are matched to ORDER BY
Date: Mon, 31 Aug 2026 23:10:00 +0000
Message-ID: <19648-25e90c26a67ae02e@postgresql.org> (raw)

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








Message-ID: <19648-25e90c26a67ae02e@postgresql.org>
Permalink:  ../19648-25e90c26a67ae02e@postgresql.org/
Also on:    postgresql.org/message-id/19648-25e90c26a67ae02e@postgresql.org

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: pgsql-bugs@postgresql.org
  Cc: noreply@postgresql.org, pgsql-bugs@lists.postgresql.org, jacobtylerwalls@gmail.com
  Subject: Re: BUG #19648: Docs on DISTINCT ON do not describe how expressions are matched to ORDER BY
  In-Reply-To: <19648-25e90c26a67ae02e@postgresql.org>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by agora; see mirroring instructions
for how to clone and mirror all data and code used for this inbox