Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.3) tls TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (Exim 4.94.2) (envelope-from ) id 1sM9f1-000rau-4r for pgsql-general@arkaria.postgresql.org; Tue, 25 Jun 2024 17:08:51 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.94.2) (envelope-from ) id 1sM9ez-00Gv59-Gf for pgsql-general@arkaria.postgresql.org; Tue, 25 Jun 2024 17:08:49 +0000 Received: from makus.postgresql.org ([2001:4800:3e1:1::229]) by malur.postgresql.org with esmtps (TLS1.3) tls TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (Exim 4.94.2) (envelope-from ) id 1sM9ez-00Gv51-5z for pgsql-general@lists.postgresql.org; Tue, 25 Jun 2024 17:08:49 +0000 Received: from sss.pgh.pa.us ([68.162.161.243]) by makus.postgresql.org with esmtps (TLS1.3) tls TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (Exim 4.94.2) (envelope-from ) id 1sM9ew-0035VU-R3 for pgsql-general@lists.postgresql.org; Tue, 25 Jun 2024 17:08:48 +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 45PH8jaB1337454; Tue, 25 Jun 2024 13:08:45 -0400 From: Tom Lane To: Bruno Wolff III cc: pgsql-general@lists.postgresql.org Subject: Re: Can any_value be used like first_value in an aggregate? In-reply-to: <20240625164208.GA1043@wolff.to> References: <20240625164208.GA1043@wolff.to> Comments: In-reply-to Bruno Wolff III message dated "Tue, 25 Jun 2024 11:42:08 -0500" MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-ID: <1337452.1719335325.1@sss.pgh.pa.us> Date: Tue, 25 Jun 2024 13:08:45 -0400 Message-ID: <1337453.1719335325@sss.pgh.pa.us> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Archived-At: Precedence: bulk Bruno Wolff III writes: > For example, is output of 10 guaranteed in the following: > bruno=> select any_value(x order by x desc) from generate_series(1,10) as x; > any_value > ----------- > 10 > (1 row) Not really. It will work that way in simple cases, but I think the behavior stops being predictable if the input gets large enough to induce the planner to use parallel aggregation. In any case, the example shown isn't amazingly efficient since it'll still perform a sort to meet the ORDER BY spec. > The use case is that I want to return a value of one column that is paired > with the maximum value of another column in each group when using GROUP BY. Use window functions (i.e. first_value). This is what they're for, and they are smart enough to do just one sort for functions sharing a common window spec. regards, tom lane