Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy a table from one database to another in Postgres

Tags:

postgresql

I am trying to copy an entire table from one database to another in Postgres. Any suggestions?

like image 677
nix Avatar asked Jul 07 '10 13:07

nix


People also ask

How do I copy a table from one database to another?

Right-click on the database name, then select "Tasks" > "Export data..." from the object explorer. The SQL Server Import/Export wizard opens; click on "Next". Provide authentication and select the source from which you want to copy the data; click "Next". Specify where to copy the data to; click on "Next".

How do I move a table in PostgreSQL?

Source database engine: Select PostgreSQL as the source database engine. Destination region: Select the destination region for the target Cloud SQL for PostgreSQL instance. Migration job type: Select the migration type that you want to perform from the drop-down list.


2 Answers

Extract the table and pipe it directly to the target database:

pg_dump -t table_to_copy source_db | psql target_db 

Note: If the other database already has the table set up, you should use the -a flag to import data only, else you may see weird errors like "Out of memory":

pg_dump -a -t table_to_copy source_db | psql target_db 
like image 54
thomax Avatar answered Sep 28 '22 11:09

thomax


You can also use the backup functionality in pgAdmin II. Just follow these steps:

  • In pgAdmin, right click the table you want to move, select "Backup"
  • Pick the directory for the output file and set Format to "plain"
  • Click the "Dump Options #1" tab, check "Only data" or "only Schema" (depending on what you are doing)
  • Under the Queries section, click "Use Column Inserts" and "User Insert Commands".
  • Click the "Backup" button. This outputs to a .backup file
  • Open this new file using notepad. You will see the insert scripts needed for the table/data. Copy and paste these into the new database sql page in pgAdmin. Run as pgScript - Query->Execute as pgScript F6

Works well and can do multiple tables at a time.

like image 26
a2ron44 Avatar answered Sep 28 '22 11:09

a2ron44