Transfer data between databases with PostgreSQL
I just had to do this exact thing so I figured I'd post the recipe here. This assumes that both databases are on the same server.
First, copy the table from the old db to the new db. At the commandline:
pg_dump -U postgres -t <old_table> <old_database> | psql -U postgres -d <new_database>
Next, grant permissions of the copied table to the user of the new database. Log into psql:
psql -U postgres -d <new_database>
ALTER TABLE <old_table> OWNER TO <new_user>;
\q
At this point your copied table in your new database still has the name <old_table>
from your old database. Assuming you want to move the data somewhere else, say to <new_table>
, you can just use regular SQL queries:
INSERT INTO <new_table> (field1, field2, field3)
SELECT field1, field2, field3 from <old_table>;
Done!
Databases are isolated in PostgreSQL; when you connect to a PostgreSQL server you connect to just one database, you can't copy data from one database to another using a SQL query.
If you come from MySQL: what MySQL calls (loosely) "databases" are "schemas" in PostgreSQL - sort of namespaces. A PostgreSQL database can have many schemas, each one with its tables and views, and you can copy from one schema to another with the schema.table
syntax.
If you really have two distinct PostgreSQL databases, the common way of transferring data from one to another would be to export your tables (with pg_dump -t
) to a file, and import them into the other database (with psql
).
If you really need to get data from a distinct PostgreSQL database, another option - mentioned in Grant Johnson's answer - is dblink, which is an additional module (in contrib/
).
Update:
Postgres introduced "foreign data wrapper" in 9.1 (which was released after the question was asked). Foreign data wrappers allow the creation of foreign tables through the Postgres FDW which makes it possible to access a remote table (on a different server and database) as if it was a local table.
This worked for me to copy a table remotely from my localhost to Heroku's postgresql:
pg_dump -C -t source_table -h localhost source_db | psql -h destination_host -U destination_user -p destination_port destination_db
This creates the table for you.
For the other direction (from Heroku to local)
pg_dump -C -t source_table -h source_host -U source_user -p source_port source_db | psql -h localhost destination_db