Received: from malur.postgresql.org ([2a02:16a8:dc51::56]) by arkaria.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.89) (envelope-from ) id 1fKm6Y-0000lM-02 for pgsql-general@arkaria.postgresql.org; Mon, 21 May 2018 14:48:06 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.89) (envelope-from ) id 1fKm6W-0001gR-HM for pgsql-general@arkaria.postgresql.org; Mon, 21 May 2018 14:48:04 +0000 Received: from makus.postgresql.org ([2001:4800:1501:1::229]) by malur.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.89) (envelope-from ) id 1fKm6W-0001gH-67 for pgsql-general@lists.postgresql.org; Mon, 21 May 2018 14:48:04 +0000 Received: from sss.pgh.pa.us ([66.207.139.130]) by makus.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.89) (envelope-from ) id 1fKm6T-0005G3-UX for pgsql-general@postgresql.org; Mon, 21 May 2018 14:48:02 +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 w4LEjRDi030940; Mon, 21 May 2018 10:45:27 -0400 From: Tom Lane To: "David G. Johnston" cc: Alexey Dokuchaev , pgsql-general Subject: Re: Aggregate functions with FROM clause and ROW_COUNT diagnostics In-reply-to: References: <20180521125441.GA85087@regency.nsu.ru> Comments: In-reply-to "David G. Johnston" message dated "Mon, 21 May 2018 07:30:44 -0700" MIME-Version: 1.0 Content-Type: text/plain; charset="UTF-8" Content-ID: <30938.1526913927.1@sss.pgh.pa.us> Content-Transfer-Encoding: quoted-printable Date: Mon, 21 May 2018 10:45:27 -0400 Message-ID: <30939.1526913927@sss.pgh.pa.us> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Precedence: bulk "David G. Johnston" writes: >> Is it possible to obtain the >> first ROW_COUNT (after SELECT) without performing it twice? > =E2=80=8BNot directly, no. You should execute the inner query to a temp= orary table > than perform your counting and json_agg from that. OP could do something like declare r record; ... select json_agg(_) as j, count(*) as c INTO r FROM ( SELECT foo, bar, baz ... FROM t1, t2, t3 WHERE ...) AS _; This would be slightly more expensive than doing only the one aggregate, but it should beat anything involving a temp table. regards, tom lane