Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a copy of a database in PostgreSQL

Tags:

postgresql

What's the correct way to copy entire database (its structure and data) to a new one in pgAdmin?

like image 907
egaga Avatar asked May 18 '09 07:05

egaga


People also ask

How do you copy data from one database to another database in Postgres?

First, make sure you are connected with both DataSources in Data Grip. Select Source Table and press F5 or (Right-click -> Select Copy Table to.) This will show you a list of all tables (you can also search using a table name in the popup window). Just select your target and press OK.


1 Answers

Postgres allows the use of any existing database on the server as a template when creating a new database. I'm not sure whether pgAdmin gives you the option on the create database dialog but you should be able to execute the following in a query window if it doesn't:

CREATE DATABASE newdb WITH TEMPLATE originaldb OWNER dbuser; 

Still, you may get:

ERROR:  source database "originaldb" is being accessed by other users 

To disconnect all other users from the database, you can use this query:

SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity  WHERE pg_stat_activity.datname = 'originaldb' AND pid <> pg_backend_pid(); 
like image 72
Bell Avatar answered Sep 25 '22 13:09

Bell