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 1na1Ue-0002by-Un for pgsql-bugs@arkaria.postgresql.org; Thu, 31 Mar 2022 20:34:08 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.92) (envelope-from ) id 1na1Ud-0001WO-SV for pgsql-bugs@arkaria.postgresql.org; Thu, 31 Mar 2022 20:34:07 +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 1na1Ud-0001PI-Lv for pgsql-bugs@lists.postgresql.org; Thu, 31 Mar 2022 20:34:07 +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 1na1Ub-0000dL-BN for pgsql-bugs@lists.postgresql.org; Thu, 31 Mar 2022 20:34:07 +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 22VKY244731796; Thu, 31 Mar 2022 16:34:02 -0400 From: Tom Lane To: Andrew D cc: pgsql-bugs@lists.postgresql.org Subject: Re: Postgres Bug - Aggregate with order by In-reply-to: References: Comments: In-reply-to Andrew D message dated "Thu, 31 Mar 2022 13:04:03 -0700" MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-ID: <731794.1648758842.1@sss.pgh.pa.us> Date: Thu, 31 Mar 2022 16:34:02 -0400 Message-ID: <731795.1648758842@sss.pgh.pa.us> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Archived-At: Precedence: bulk Andrew D writes: > I believe that I've found a bug within postgres where an aggregate function > is not accepted when an order by clause is specified, here is a short > example: > postgres=# select COUNT(i) from test_table order by i; > ERROR: column "test_table.i" must appear in the GROUP BY clause or be used > in an aggregate function > LINE 1: select COUNT(i) from test_table order by i; > ^ This looks perfectly normal to me. The ORDER BY clause is supposed to be performed after the aggregation step. But there's no meaningful value of i to associate with the aggregated rows (well, row, in this case). It's not very clear what you were hoping to accomplish, but if you intended to sort before the aggregation, the correct way is to write select COUNT(i order by i) from test_table; (Ordering the input to COUNT() is pretty pointless, of course, but there are other aggregates for which it's useful to do this.) regards, tom lane