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 1kn1Et-0004Hu-UG for pgsql-general@arkaria.postgresql.org; Wed, 09 Dec 2020 15:18:47 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.92) (envelope-from ) id 1kn1EM-00058Z-UN for pgsql-general@arkaria.postgresql.org; Wed, 09 Dec 2020 15:18:14 +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 1kn1EM-00058R-MW for pgsql-general@lists.postgresql.org; Wed, 09 Dec 2020 15:18:14 +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 1kn1EG-0002z4-Dd for pgsql-general@lists.postgresql.org; Wed, 09 Dec 2020 15:18:13 +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 0B9FI6AK3578730; Wed, 9 Dec 2020 10:18:06 -0500 From: Tom Lane To: Wolfgang Walther cc: pgsql-general@lists.postgresql.org Subject: Re: Execution order of CTEs / set_config and current_setting in the same query In-reply-to: References: Comments: In-reply-to Wolfgang Walther message dated "Wed, 09 Dec 2020 14:42:43 +0100" MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-ID: <3578728.1607527086.1@sss.pgh.pa.us> Date: Wed, 09 Dec 2020 10:18:06 -0500 Message-ID: <3578729.1607527086@sss.pgh.pa.us> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Precedence: bulk Wolfgang Walther writes: > Now, we are wondering: To reduce overhead, can we move the set_config > calls to a CTE as part of the main query? The values would need to be > available with current_setting(...) in the remaining query. I think you're on fairly shaky ground here. Generally speaking, a CTE will be executed/read only when the parent query needs the next row from it. Your examples ensure that the CTE is read before the parent query's results are computed; but in realistic usage you'd presumably be joining the CTE with some other table(s), and then the execution order is going to be a lot harder to predict. This approach is also going to fundamentally not work for settings that need to apply during planning of the query (which, notably, probably includes "role"). You'd be far better off to investigate ways to send SET LOCAL first, without incurring a separate network round trip for that. If you're using simple query mode that's easy, you can just do res = PQexec("SET LOCAL ... ; "); In extended query mode you can't get away with that, but you might be able to issue the SET LOCAL without immediately waiting for the result. regards, tom lane