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 1mG4GZ-0004RV-Fo for pgsql-bugs@arkaria.postgresql.org; Tue, 17 Aug 2021 18:56:51 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.92) (envelope-from ) id 1mG4GY-0000um-6Q for pgsql-bugs@arkaria.postgresql.org; Tue, 17 Aug 2021 18:56:50 +0000 Received: from makus.postgresql.org ([2001:4800:3e1:1::229]) by malur.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1mG4GX-0000ue-W2 for pgsql-bugs@lists.postgresql.org; Tue, 17 Aug 2021 18:56:49 +0000 Received: from sss.pgh.pa.us ([66.207.139.130]) by makus.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1mG4GT-0007Qb-0Y for pgsql-bugs@lists.postgresql.org; Tue, 17 Aug 2021 18:56:49 +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 17HIuhEj1369912; Tue, 17 Aug 2021 14:56:43 -0400 From: Tom Lane To: "David G. Johnston" cc: "luy70@psu.edu" , "pgsql-bugs@lists.postgresql.org" Subject: Re: BUG #17150: Unexpected outputs from the query In-reply-to: References: <17150-d22e14860d93d32e@postgresql.org> Comments: In-reply-to "David G. Johnston" message dated "Tue, 17 Aug 2021 11:27:10 -0700" MIME-Version: 1.0 Content-Type: text/plain; charset="UTF-8" Content-ID: <1369910.1629226603.1@sss.pgh.pa.us> Content-Transfer-Encoding: 8bit Date: Tue, 17 Aug 2021 14:56:43 -0400 Message-ID: <1369911.1629226603@sss.pgh.pa.us> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Archived-At: Precedence: bulk "David G. Johnston" writes: > On Tuesday, August 17, 2021, PG Bug reporting form > wrote: >> This >> unexpected return can be fixed by removing "ORDER BY ( SELECT COUNT ( v1 ) >> )", then the query returns sum="0" as expected. > Well, PostgreSQL cannot remove the order by otherwise it would be a > different query. So your suggestion is spot on, and the user should > probably do that, but it doesn’t seem like a bug. Yeah. PG interprets SELECT x FROM v2 ORDER BY (SELECT COUNT(v1)) to behave the same as SELECT x, (SELECT COUNT(v1)) FROM v2 ORDER BY 2 (modulo the fact that the ORDER BY column won't be output), and then it turns out that that's effectively the same as SELECT x, COUNT(v1) FROM v2 ORDER BY 2 the reason being that since v1 is a variable of the outer query, the aggregate is considered to be an aggregate of the outer query *not* the sub-select. (That's required by the SQL standard.) So at this point you have an aggregated query that is certain to return 1 row, not more or less, regardless of how many rows are returned by v2. regards, tom lane