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

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.


This helped me solve my problem:

SELECT *, pg_terminate_backend(procpid) 
FROM pg_stat_activity 
WHERE usename='username';

--Use pid if PostgreSQL version 9.2 or above.

I terminated all active connections to template1 and could create database normally


You can also try to terminate the current process thread by the Terminal

Search the Process :

sudo ps aux | grep template1

Kill the Process :

sudo kill -9 < your process id >


To solve this, I have to disconnect the database connection from the pgAdmin III.


I have a script that connects to a database and performs various operations on it, some requiring that no one else is logged in. I modified @Andrius's answer not to terminate my script's connection, but rather terminate everyone else's:

SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE pid <> pg_backend_pid();

From the docs: pg_backend_pid() is the Process ID of the server process attached to the current session.