Terminate (kill) specific session in PostgreSQL database

PostgreSQL provides function to terminate specific session on a server.

Find session ID (pid)

First we will identify the session we want to end. We do it by listing all sessions on the server with this query:

select * from pg_stat_activity;

Result

Result shows active sessions on server.

sample results

Kill session

Now we will use process ID (pid) to kill the session (18765 in our example):

select pg_terminate_backend(pid) 
from pg_stat_activity
where pid = '18765';

Result

PostgreSQL ends session and rolls back all transactions that are associated with it. sample results