postgresql - can't create database - OperationalError: source database "template1" is being accessed by other users

Andrius picture Andrius · Jan 17, 2013 · Viewed 57.5k times · Source

I logged in to source database template1 and now I can't create database. When I try to create database, I get this error:

OperationalError: source database "template1" is being accessed by other users
DETAIL:  There are 5 other session(s) using the database.

Every time I login to template1, I use 'exit' command to logout, but as you can see it does not logout and number of sessions increases everytime I login. Is there a way to force disconnect every connection to template1 that logged in now?

Answer

mvp picture mvp · Jan 17, 2013

Database template1 exists only to provide barebone structure to create another empty database. You should never logon to template1, otherwise you will have problems.

Probably easiest solution for you is to restart PostgreSQL server process, and logon again. Database that should always exist and is safe to logon is postgres.

If restarting is not an option, you can use another emergency template database: template0.

By default, this statement:

CREATE DATABASE dbname;

is equivalent to:

CREATE DATABASE dbname TEMPLATE template1;

If template1 is not available or corrupted, you can use template0 as last resort:

CREATE DATABASE dbname TEMPLATE template0;

You can read more about template databases here.