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 1mLw2m-0000HU-MZ for pgsql-general@arkaria.postgresql.org; Thu, 02 Sep 2021 23:22:52 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.92) (envelope-from ) id 1mLw2l-0001rl-Aa for pgsql-general@arkaria.postgresql.org; Thu, 02 Sep 2021 23:22:51 +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 1mLw2l-0001rc-1j for pgsql-general@lists.postgresql.org; Thu, 02 Sep 2021 23:22:51 +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 1mLw2i-0005Gu-Un for pgsql-general@lists.postgresql.org; Thu, 02 Sep 2021 23:22:50 +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 182NMkGg2441708; Thu, 2 Sep 2021 19:22:46 -0400 From: Tom Lane To: "David G. Johnston" cc: Shubham Mittal , PostgreSQL General Subject: Re: Query takes around 15 to 20 min over 20Lakh rows In-reply-to: References: Comments: In-reply-to "David G. Johnston" message dated "Thu, 02 Sep 2021 16:08:52 -0700" MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-ID: <2441706.1630624966.1@sss.pgh.pa.us> Date: Thu, 02 Sep 2021 19:22:46 -0400 Message-ID: <2441707.1630624966@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 Thu, Sep 2, 2021 at 3:16 PM Shubham Mittal > wrote: >> *Please help in optimizing this query. I need to actually generate reports >> daily using this query.. It takes almost 15 to 20 min to execute this query >> due to joins.. * > Use jsonb_populate_recordset (or one of its siblings) to get rid of as many > of these key-based value extraction operations as possible and build a > table from the contents of the jsonb. While those duplicative extractions sure look inefficient, it's not clear from the (lack of) given facts whether that's the main cost, or whether the complicated FROM clause is producing a bad plan. I'd suggest first looking at EXPLAIN ANALYZE output to verify which plan step(s) are slow. If it's the final output step that's expensive, then yes the next step is to optimize the extractions. Otherwise, see https://wiki.postgresql.org/wiki/Slow_Query_Questions regards, tom lane