Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kill a postgresql session/connection

How can I kill all my postgresql connections?

I'm trying a rake db:drop but I get:

ERROR:  database "database_name" is being accessed by other users DETAIL:  There are 1 other session(s) using the database. 

I've tried shutting down the processes I see from a ps -ef | grep postgres but this doesn't work either:

kill: kill 2358 failed: operation not permitted 
like image 965
DanS Avatar asked Feb 24 '11 18:02

DanS


People also ask

How do I stop a Postgres session?

The meta-command for exiting psql is \q .

How do you kill a session in Pgadmin?

You can use pg_terminate_backend() to kill a connection. You have to be superuser to use this function. This works on all operating systems the same. Note that in Postgres 9.2, procpid is renamed to pid.

How do I kill idle connections in PostgreSQL?

If the count is greater than 600 overall, you can run below query to clean up the idle connections: SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = 'postgres' AND pid <> pg_backend_pid() AND state in ('idle');

How do I turn off active connections in PostgreSQL?

How to kill all other active connections to your database in PostgreSQL? Using SQL Query, run the query below: SELECT pg_terminate_backend(pg_stat_activity. pid) FROM pg_stat_activity WHERE pg_stat_activity.


1 Answers

You can use pg_terminate_backend() to kill a connection. You have to be superuser to use this function. This works on all operating systems the same.

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'     ; 

Before executing this query, you have to REVOKE the CONNECT privileges to avoid new connections:

REVOKE CONNECT ON DATABASE dbname FROM PUBLIC, username; 

If you're using Postgres 8.4-9.1 use procpid instead of pid

SELECT      pg_terminate_backend(procpid)  FROM      pg_stat_activity  WHERE      -- don't kill my own connection!     procpid <> pg_backend_pid()     -- don't kill the connections to other databases     AND datname = 'database_name'     ; 
like image 153
Frank Heikens Avatar answered Sep 19 '22 11:09

Frank Heikens