[PostgreSQL] Create a database from an exist database

Table of Content

[PostgreSQL] Create a database from an exist database

Create a database

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;

Disconnect all other users from the database

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();

References

  1. https://stackoverflow.com/questions/876522/creating-a-copy-of-a-database-in-postgresql
  2. https://dothanhlong.org/force-drop-database-postgresql/

Leave a Reply

Your email address will not be published.