1

I want to copy some records from one database to another in separate environment (eg copying over data from dev instance to production instance). These DB shares the same schema.

We have two tables with foreign keys. As a example, we have table users and user_emails so we have records like

select * users
id | name
1 | John
2 | Kevin
select * user_emails
id | user_id | email
1  | 1 | [email protected]
2  | 1 | [email protected]

Now I want to copy certain users and their email to another database. Note id (primary key) of user and user_emails record will change after copy because other database already have some records. What is the easiest way to achieve this task?

1
  • Do u store data in online db mode or offline... Commented Sep 21, 2022 at 3:06

1 Answer 1

1
+50

If you have unique column "name" than run the below command to install dblink extension

create extension if not exists  dblink;

First we will get the data from remote server using dblink and store result in cte

with cte_remote_data as (SELECT * FROM dblink('host=remotostip/name port=remote_port user=remote_user password=remote_password dbname=remot_dbname','select name,email from users u join user_emails ue on u.id=ue.user_id')AS data( name text,email text))
select * from cte_remote_data 

this will give select result from the remote database Now insert these name in users table and get inserted id,name using another cte_ins_usr

cte_ins_usr as(insert into users(name)  select name from cte_remote_data returning name,id)

now join cte_ins_usr with name with cte_remote_data on name (assuming that name is unique in table) and insert in user_email table

insert into user_emails(user_id,email) select id,email from cte_remote_data crd join cte_ins_usr ciu on crd.name=ciu.name returning *

All in one for your case:

with cte_remote_data as (SELECT * FROM dblink('host=remotostip/name port=remote_port user=remote_user password=remote_password dbname=remot_dbname','select name,email from users u join user_emails ue on u.id=ue.user_id')AS data( name text,email text)),
cte_ins_usr as(insert into users(name)  select name from cte_remote_data returning name,id)
insert into user_emails(user_id,email) select id,email from cte_remote_data crd join cte_ins_usr ciu on crd.name=ciu.name returning *

will do job for you

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.