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 1jroJT-0004yu-Bl for pgsql-general@arkaria.postgresql.org; Sat, 04 Jul 2020 19:59:03 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.92) (envelope-from ) id 1jroJR-0006FG-VO for pgsql-general@arkaria.postgresql.org; Sat, 04 Jul 2020 19:59:01 +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 1jroJR-0006F5-Nl for pgsql-general@lists.postgresql.org; Sat, 04 Jul 2020 19:59:01 +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 1jroJP-00018K-An for pgsql-general@postgresql.org; Sat, 04 Jul 2020 19:59:00 +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 064JwuAe1206018; Sat, 4 Jul 2020 15:58:56 -0400 From: Tom Lane To: Mohamed Wael Khobalatte cc: pgsql-general@postgresql.org Subject: Re: Degraded performance during table rewrite In-reply-to: References: <1115603.1593811564@sss.pgh.pa.us> <1154267.1593829869@sss.pgh.pa.us> Comments: In-reply-to Mohamed Wael Khobalatte message dated "Sat, 04 Jul 2020 15:34:19 -0400" MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-ID: <1206016.1593892736.1@sss.pgh.pa.us> Date: Sat, 04 Jul 2020 15:58:56 -0400 Message-ID: <1206017.1593892736@sss.pgh.pa.us> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Precedence: bulk Mohamed Wael Khobalatte writes: > Tom, I think I understood what you meant after getting some sleep. What I > do now is: > - Initially load a lot of ids, say a million. > - Then I slice that array by my preferred batch, say a 10000. > - Loop through these slices and run an improved query, which looks like > this: > WITH del AS ( > DELETE FROM #{old_table} > WHERE id >= #{first_id_in_slice} AND id <= #{last_id_in_slice} > RETURNING * > ) > INSERT INTO #{table} > SELECT * FROM del > RETURNING id Right, the problem occurs when you're deleting stuff that's at the end of the id range, and have already deleted stuff that was previously the end of the range. If you start somewhere in the middle and work towards the end, you dodge that problem, even for the very last delete that *is* handling the endmost ids. regards, tom lane