How to Copy a Database in PostgreSQL?
Copying a database in PostgreSQL can be done in several ways, such as using the CREATE DATABASE ... WITH TEMPLATE command, the pg_dump and pg_restore utilities, or psql. Here’s a step-by-step guide on each method, with examples and explanations.
1. Using the CREATE DATABASE Command with TEMPLATE
One way to create an exact copy of a database in PostgreSQL is by using the CREATE DATABASE command with the TEMPLATE option.
Syntax:
CREATE DATABASE new_database WITH TEMPLATE original_database;
Example Code:
-- Create a copy of the database named original_db
CREATE DATABASE new_db WITH TEMPLATE original_db; -- Copies the structure and data from original_db to new_db
Explanation:
Note: This approach requires that no active connections exist to the template database (original_db). Use this method when both databases are on the same PostgreSQL instance and when you want an identical clone.
2. Using pg_dump and pg_restore to Copy Database Across Servers
If you need to copy a database to a different server, you can use the pg_dump and pg_restore utilities to export and import data.
Steps:
Example Code:
a. Exporting the database:
# Create a backup of original_db to original_db.bak file
pg_dump -U postgres -F c -d original_db -f /path/to/original_db.bak
Explanation:
b. Restoring the database:
# Restore the backup to create a new database named new_db
pg_restore -U postgres -d new_db /path/to/original_db.bak
Explanation:
3. Using psql with pg_dump to Copy Database
If pg_restore is not available or if you’re copying a smaller database, you can use pg_dump with psql.
Example Code:
a. Exporting the database:
# Dump original_db to a plain SQL file
pg_dump -U postgres -d original_db -f /path/to/original_db.sql
b. Restoring with psql:
# Create a new database and import the SQL file
createdb -U postgres new_db # Create the new database
psql -U postgres -d new_db -f /path/to/original_db.sql # Import data
Explanation:
Important Notes
All PostgreSQL Questions, Answers, and Code Snippets Collection.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4