Skip to content

Instantly share code, notes, and snippets.

@mchoiruln
Last active October 1, 2021 17:32
Show Gist options
  • Save mchoiruln/b4c1ada4d671ecb6a4fc364ae6c830cf to your computer and use it in GitHub Desktop.
Save mchoiruln/b4c1ada4d671ecb6a4fc364ae6c830cf to your computer and use it in GitHub Desktop.
Cloning DB with existing database via templating system postgresql

Postgres allows the use of any existing database on the server as a template when creating a new database.

CREATE DATABASE new_db WITH TEMPLATE original_db OWNER postgres;

Still, you may get:

ERROR:  source database "original_db" 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 = 'original_db' AND pid <> pg_backend_pid();

#source : creating-a-copy-of-a-database-in-postgresql

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment