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 1jYspK-0006QT-I1 for pgsql-general@arkaria.postgresql.org; Wed, 13 May 2020 14:57:42 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.92) (envelope-from ) id 1jYspJ-00087I-52 for pgsql-general@arkaria.postgresql.org; Wed, 13 May 2020 14:57:41 +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 1jYspI-00083O-Se for pgsql-general@lists.postgresql.org; Wed, 13 May 2020 14:57:40 +0000 Received: from sss.pgh.pa.us ([66.207.139.130]) by magus.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1jYspG-0007IN-Bh for pgsql-general@lists.postgresql.org; Wed, 13 May 2020 14:57:40 +0000 Received: from sss1.sss.pgh.pa.us (localhost [127.0.0.1]) by sss.pgh.pa.us (8.14.4/8.14.4) with ESMTP id 04DEvUdx000960; Wed, 13 May 2020 10:57:30 -0400 From: Tom Lane To: Tom Ellis cc: pgsql-general@lists.postgresql.org Subject: Re: Why is it that =?utf-8?B?4oCcYWdncmVnYXRl?= =?utf-8?Q?_functions_are_not_allowed_in_FROM_clause_of_their_own_query_l?= =?utf-8?B?ZXZlbOKAnT8=?= In-reply-to: <20200513110251.GC24083@cloudinit-builder> References: <20200513110251.GC24083@cloudinit-builder> Comments: In-reply-to Tom Ellis message dated "Wed, 13 May 2020 12:02:51 +0100" MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-ID: <958.1589381850.1@sss.pgh.pa.us> Date: Wed, 13 May 2020 10:57:30 -0400 Message-ID: <959.1589381850@sss.pgh.pa.us> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Precedence: bulk Tom Ellis writes: > A. Am I right in thinking that the two forms are equivalent? No. In the first case the SUM() aggregate does not use any variables belonging to the "LATERAL (SELECT ..." query level, therefore, per SQL standard, it is not an aggregate of that query but an aggregate of the next query level up, whose variable(s) it does use. And within the structure of *that* query level, it's in the wrong place. > A1. And am I right to presume that it's always possibly to rewrite > more complicated examples that yield the same error to valid versions, > just by coming up with a local name for the problematic fields? In the particular case here, the problem is to control which query level the aggregate is deemed to belong to. I think the issue is less about "can I rewrite the query" and more about "do I actually understand the semantics this is asking for", so I'd be hesitant to let a tool think that it can rearrange things like this. regards, tom lane