pg.ddx.io  pgsql-general@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Tom Lane <tgl@sss.pgh.pa.us>
To: mirabilos <tg@evolvis.org>
Cc: pgsql-general@lists.postgresql.org
Subject: Re: DISTINCT *and* ORDER BY in aggregate functions on expressions(!)
Date: Mon, 27 Feb 2023 19:11:05 -0500
Message-ID: <532894.1677543065@sss.pgh.pa.us> (raw)
In-Reply-To: <23d08470-aaa8-afca-dfd7-37261487a1f8@evolvis.org>
References: <23d08470-aaa8-afca-dfd7-37261487a1f8@evolvis.org>

mirabilos <tg@evolvis.org> writes:
> This works well. However, what I seem to be not allowed to do is
> (without the extra COALESCE, to simplify):
> ...
> This is because, when I use DISTINCT (but only then‽), the ORDER BY
> arguments must be… arguments to the function, or something.

Well, yeah.  Simplify it to

  SELECT array_agg(DISTINCT x ORDER BY y) FROM mytable;

If there are several rows containing the same value of x and different
values of y, which y value are we supposed to sort the unique-ified x
value by?  It's an ill-defined query.

For the specific example you give, it's true that any specific
possible output of jsonb_build_object() would correspond to
a unique set of cot.weekday, cot.from_hour, cot.to_hour values.
But the parser can't be expected to know that.  Many functions
can produce the same output for different sets of inputs.

I'd suggest moving the distinct-ification into an earlier
processing step (i.e. a sub-select), or maybe thinking harder
about why you're getting duplicates in the first place.

			regards, tom lane





view thread (14+ messages)  latest in thread

Message-ID: <532894.1677543065@sss.pgh.pa.us>
Permalink:  ../532894.1677543065@sss.pgh.pa.us/
Also on:    postgresql.org/message-id/532894.1677543065@sss.pgh.pa.us

 · 

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 from your mail client; the link fills in
  the headers below: reply via email
  Some clients, webmail especially, drop In-Reply-To and References from
  a link, and the reply then starts a new thread: use the mbox below.

  To: pgsql-general@postgresql.org
  Cc: tgl@sss.pgh.pa.us, tg@evolvis.org
  Subject: Re: DISTINCT *and* ORDER BY in aggregate functions on expressions(!)
  In-Reply-To: <532894.1677543065@sss.pgh.pa.us>
  References: <23d08470-aaa8-afca-dfd7-37261487a1f8@evolvis.org> <532894.1677543065@sss.pgh.pa.us>

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

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