How to kill PostgreSQL process/session/connection

In this article, we will see how to kill PostgreSQL process ID step by step. we can kill process id by using the function pg_terminate_backend(). To execute this, we must must have superuser privileges.

Query to kill Postgres Process:

SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE — don’t kill my own connection! pid <> pg_backend_pid() — don’t kill the connections to other databases AND datname = ‘database_name’;

Where datname = ‘database_name’ which will kills connections of this database only.
Note: For older versionsreplace pid with procid

Examples to kill PostgreSQL process:

1. Lets see list of process in PostgreSQL server by running below query.

select pid,usename, datname from pg_stat_activity;

2. Lets, kill process id 6516 from the above list using below query. To run this query, user must have superuser privileges’.

SELECT pg_terminate_backend(6516) FROM pg_stat_activity WHERE — don’t kill my own connection! pid <> pg_backend_pid() — don’t kill the connections to other databases AND datname = ‘db13’;

if output of this query is t then process killed successfully.

3. Lets verify process is killed or not.

select pid,usename, datname from pg_stat_activity;

4. After running above command and not able to kill process, then last option is to restart the PostgreSQL server using below command or kill -8 procid. Surely this will be done if business is down. Before doing this take proper guidance from your serniors.

sudo service postgresql restart or sudo systemctl restart postgresql

So in this article, we have have query and example to kill PostgreSQL process.