Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1pWnaa-00005E-Uk for pgsql-general@arkaria.postgresql.org; Tue, 28 Feb 2023 00:11:28 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.92) (envelope-from ) id 1pWnaZ-00047n-7Y for pgsql-general@arkaria.postgresql.org; Tue, 28 Feb 2023 00:11:27 +0000 Received: from magus.postgresql.org ([2a02:c0:301:0:ffff::29]) by malur.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1pWnaY-00047d-T6 for pgsql-general@lists.postgresql.org; Tue, 28 Feb 2023 00:11:26 +0000 Received: from sss.pgh.pa.us ([66.207.139.130]) by magus.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1pWnaS-0006yC-J8 for pgsql-general@lists.postgresql.org; Tue, 28 Feb 2023 00:11:24 +0000 Received: from sss1.sss.pgh.pa.us (localhost [127.0.0.1]) by sss.pgh.pa.us (8.15.2/8.15.2) with ESMTP id 31S0B5P4532895; Mon, 27 Feb 2023 19:11:05 -0500 From: Tom Lane To: mirabilos cc: pgsql-general@lists.postgresql.org Subject: Re: DISTINCT *and* ORDER BY in aggregate functions on expressions(!) In-reply-to: <23d08470-aaa8-afca-dfd7-37261487a1f8@evolvis.org> References: <23d08470-aaa8-afca-dfd7-37261487a1f8@evolvis.org> Comments: In-reply-to mirabilos message dated "Tue, 28 Feb 2023 00:11:49 +0100" MIME-Version: 1.0 Content-Type: text/plain; charset="UTF-8" Content-ID: <532893.1677543065.1@sss.pgh.pa.us> Content-Transfer-Encoding: 8bit Date: Mon, 27 Feb 2023 19:11:05 -0500 Message-ID: <532894.1677543065@sss.pgh.pa.us> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Archived-At: Precedence: bulk mirabilos 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