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 1ocDVp-0004IA-Si for pgsql-general@arkaria.postgresql.org; Sat, 24 Sep 2022 22:20:41 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.92) (envelope-from ) id 1ocDVo-00087l-N5 for pgsql-general@arkaria.postgresql.org; Sat, 24 Sep 2022 22:20:40 +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 1ocDVo-00086T-B5 for pgsql-general@lists.postgresql.org; Sat, 24 Sep 2022 22:20:40 +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 1ocDVl-0006A4-TR for pgsql-general@lists.postgresql.org; Sat, 24 Sep 2022 22:20:39 +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 28OMKZYY2617337; Sat, 24 Sep 2022 18:20:35 -0400 From: Tom Lane To: Federico cc: pgsql-general@lists.postgresql.org Subject: Re: Order by in a sub query when aggregating the main query In-reply-to: References: Comments: In-reply-to Federico message dated "Sat, 24 Sep 2022 23:38:21 +0200" MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-ID: <2617335.1664058035.1@sss.pgh.pa.us> Date: Sat, 24 Sep 2022 18:20:35 -0400 Message-ID: <2617336.1664058035@sss.pgh.pa.us> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Archived-At: Precedence: bulk Federico writes: > A basic example of the type of query in question is the following (see > below for the actual query): > select w, array_agg(x) > from ( > select v, v / 10 as w > from pg_catalog.generate_series(25, 0, -1) as t(v) > order by v > ) as t(x) > group by w > This query will return an ordered array as specified by the order by > clause.in the subquery. > Can this behaviour be relied upon? No, not really. It might always work given a particular set of circumstances. As long as the planner chooses to do the outer query's grouped aggregation as a HashAgg, there'd be no reason for it to reshuffle the subquery output before feeding that to array_agg. However, if it decided that sort-group-and-aggregate was better, it'd insert a sort by w above the subquery, and then you'd lose any certainty of the ordering by v continuing to hold. (Maybe the sort by w would be stable for equal keys, but that's not guaranteed.) What you really ought to do is write select w, array_agg(x order by x) from ... to be in the clear per SQL standard. I think that right now that'd incur additional sorting overhead, which is annoying. But work is ongoing to recognize when the input is already correctly sorted for an aggregate, so it should get better in PG 16 or so. regards, tom lane