PostgreSQL Copy Database Made Easy
Summary: in this tutorial, you will learn how to copy a PostgreSQL database on the same server or from one server to another.
PostgreSQL copy database within the same server
Sometimes, you want to copy a PostgreSQL database within a database server for testing purposes.
PostgreSQL makes it easy to do so via the CREATE DATABASE
statement, as follows:
This statement copies the sourcedb
to the targetdb
. For example, to copy the dvdrental
sample database to the dvdrental_test
database, you use the following statement:
Depending on the size of the source database, copying may take some time to complete.
If the dvdrental
database has active connections, you will encounter the following error:
The following query returns the active connections:
To terminate the active connections to the dvdrental
database, you use the following query:
After that, you can execute the CREATE TABLE WITH TEMPLATE
statement again to copy the dvdrental
database to dvdrental_test
database.
PostgreSQL copy database from one server to another
There are several ways to copy a database between PostgreSQL database servers.
If the size of the source database is big and the connection between the database servers is slow, you can dump the source database to a file, copy the file to the remote server, and restore it:
First, dump the source database into a file.
Second, copy the dump file to the remote server.
Third, create a new database in the remote server:
Finally, restore the dump file on the remote server:
Copying the dvdrental database example
The following steps illustrate how to copy the dvdrental
database from the local server to the remote
server.
First, dump the dvdrental
database into a dump file such as dvdrental.sql
:
Second, copy the dump file to the remote
server.
Third, create the dvdrental
database on the remote
server:
Fourth, restore the dvdrental.sql
dump file in the remote
server:
If the connection between the servers is fast and the size of the database is not big, you can use the following command:
For example, to copy the dvdrental
database from the localhost
server to the remote
server, you can execute the following command:
In this tutorial, you have learned how to copy a PostgreSQL database within a database server, or from one database server to another.