From: Ron <ronljohnsonjr@gmail.com>
To: pgsql-general@lists.postgresql.org
Subject: Re: How to copy rows into same table efficiently
Date: Tue, 26 Oct 2021 04:05:53 -0500
Message-ID: <982cf46b-c112-82cb-3f34-6904305761bb@gmail.com> (raw)
In-Reply-To: <CA+7NA6aNAAKByWQ9yNN9kq7nDDk3+eyT95Ur9g60nRshmu8-xQ@mail.gmail.com>
References: <CA+7NA6aNAAKByWQ9yNN9kq7nDDk3+eyT95Ur9g60nRshmu8-xQ@mail.gmail.com>
On 10/26/21 1:04 AM, Arun Suresh wrote:
>
> Dear PG experts,
>
> We have a tenant discriminator column in our tables to enable storage of
> data from multiple
> tenants. This column is also part of the composite primary key.
> The customers may request creation of a tenant copy, which means if they
> currently have a
> tenant id "ABCD", they would like to copy all data "where tenant_id =
> 'ABCD'" to a new copy tenant "XYZ".
> The copy must also be done on the same table.
>
> Current approach taken is to build a query like below:
> INSERT INTO mytable (col1, col2, col3, col4) SELECT col1, 'XYZ', col3,
> col4 FROM mytable WHERE col2 = 'ABCD'
>
> Is there a better way to do this?
> There could be other tables with foreign key reference, would a simple
> ordering of the copy based on table relationship suffice?
That would be my first thought. Of course, FK dependencies quickly become a
rat's nest, so beware.
> Also if the table has millions of records, what are the things to take
> care of?
Take care of?
Anyway, for millions of rows, I might use COPY instead of INSERT (depending
on how many millions, how many indices, how large the rows, how fast the
machine, etc.
--
Angular momentum makes the world go 'round.
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients from your mail client; the link fills in
the headers below: reply via email
Some clients, webmail especially, drop In-Reply-To and References from
a link, and the reply then starts a new thread: use the mbox below.
To: pgsql-general@postgresql.org
Cc: ronljohnsonjr@gmail.com
Subject: Re: How to copy rows into same table efficiently
In-Reply-To: <982cf46b-c112-82cb-3f34-6904305761bb@gmail.com>
References: <CA+7NA6aNAAKByWQ9yNN9kq7nDDk3+eyT95Ur9g60nRshmu8-xQ@mail.gmail.com> <982cf46b-c112-82cb-3f34-6904305761bb@gmail.com>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox