Sample Header Ad - 728x90

How can I export PostgreSQL data from multiple tables joined by foreign keys, preferably as insert statements?

0 votes
0 answers
122 views
I'd like to automate exporting data from one database to be inserted to another. The data is stored in multiple tables joined by foreign keys, so rows from the parent table need to be inserted by for the child tables. An example: Tables: create table table_a (id bigserial primary key, a_name text null ); create table table_b (id bigserial primary key, b_name text null, table_a_id bigint not null references table_a); create table table_c (id bigserial primary key, c_name text null, table_b_id bigint not null references table_b); Now I want to select all the data associated with table_a.id = 1 that for table_a, I can select all of that data following foreign keys using: select * from table_a ta join table_b tb on ta.id = tb.table_a_id join table_c tc on tb.id = tc.table_b_id and ta.id = 1; I get: id,a_name,id,b_name,table_a_id,id,c_name,table_b_id 1,a_test,2,b_test,1,1,c_test,2 But is there a way to export all of the data in a way that is easy to import into another database? My rich db client (DatGrip) can export data but only one table at a time and my real example has far more than 3 tables I need to export. Ideally I would like insert statements but csv is okay if it works. I'll assume that there won't be any primary key conflicts. Thanks for your help!
Asked by Kramer (101 rep)
Jul 11, 2024, 06:46 PM
Last activity: Jul 11, 2024, 10:41 PM