This article is half-done without your Comment! *** Please share your thoughts via Comment ***
IIn this post, I am sharing a script to make a copy of the PostgreSQL database.
We can also create copies of the database using the pgAdmin tool, but I always preferred to use and create SQL script to perform the Database Administrator related activities.
In the development environment, I am following a practice that after every release of the sprint, I take backup of the database and as well as create the previous version of the database.
If any user wants to check existing functionality in the previous version, they can test with an old version of the database.
Below is a script to make a copy of an existing database:
1 |
CREATE DATABASE newDB WITH TEMPLATE oldDB OWNER dbUser; |
After executing this,
If you get any error, you should kill all the running sessions of that existing database.
1 |
ERROR: source database "originaldb" is being accessed by other users |
You can use below script to kill all running sessions:
You can also visit this article.
1 2 3 4 |
SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE datname = 'datbase_name' AND pid <> pg_backend_pid(); |