542

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
Ondrej Machulda
  • 998
  • 1
  • 12
  • 24
DanS
  • 17,550
  • 9
  • 53
  • 47
  • When all other attempts failed, the pgreset gem somehow fixed rails/pg thinking a connection existed, which did not. – JosephK Jun 10 '20 at 14:48

25 Answers25

993

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'
    ;
notpeter
  • 1,046
  • 11
  • 16
Frank Heikens
  • 117,544
  • 24
  • 142
  • 135
  • 85
    Note that in Postgres 9.2, procpid is renamed to pid. – Devin Dec 04 '12 at 22:39
  • 1
    If he was a superuser, couldn't he have `sudo`-ed the kill anyway? – ndnenkov Mar 11 '16 at 14:45
  • 3
    @ndn A database superuser is not the same thing as an OS level superuser. There is no `sudo` in PG. – jpmc26 Jul 29 '16 at 15:36
  • This is the only working answer for many SO questions because it has the `REVOKE` step. You saved someone, one more time I guess ! – AymDev Aug 15 '19 at 22:07
  • 1
    I think you can use `SELECT pg_terminate_backend(pid)` to kill your own connections even if you're not a superuser, however, doing `REVOKE CONNECT ON DATABASE` is probably not the best idea for your own user :) – Peter Kilczuk Nov 25 '20 at 10:32
  • This solution does NOT work if you have pgAdmin4 opened and connected to the server. See the answer here for this problem: https://dba.stackexchange.com/questions/11893/force-drop-db-while-others-may-be-connected – M46 Feb 24 '21 at 15:37
  • SELECT pg_cancel_backend(__pid__); is a much safer alternative – cluis92 Mar 15 '21 at 22:43
  • @cluis92: pg_cancel_backend() is a different function that does a different thing: It just cancels a current query, but it doesn't kill the database connection. It's not safer, it's just different. – Frank Heikens Mar 16 '21 at 08:58
  • hi, why is that we are not able to login after executing the above query to terminate all the current users? Now none of my users are able login to the db. The details can be found here https://stackoverflow.com/questions/68411306/how-to-login-to-postgresql-db-after-session-kill-for-copy-database – The Great Jul 16 '21 at 15:20
  • *This* deserve a coffee – SuperPoney Oct 29 '21 at 09:51
271

Maybe just restart postgres => sudo service postgresql restart

Haris Krajina
  • 14,824
  • 12
  • 64
  • 81
65

With all infos about the running process:

SELECT *, pg_terminate_backend(pid)
FROM pg_stat_activity 
WHERE pid <> pg_backend_pid()
AND datname = 'my_database_name';
Dorian
  • 22,759
  • 8
  • 120
  • 116
28

MacOS, if postgresql was installed with brew:

brew services restart postgresql

Source: Kill a postgresql session/connection

Juuso Ohtonen
  • 8,826
  • 9
  • 65
  • 98
19

Easier and more updated way is:

  1. Use ps -ef | grep postgres to find the connection #
  2. sudo kill -9 "#" of the connection

Note: There may be identical PID. Killing one kills all.

Jake Worth
  • 5,490
  • 1
  • 25
  • 35
Mr. Rene
  • 1,167
  • 10
  • 17
14

OSX, Postgres 9.2 (installed with homebrew)

$ launchctl unload -w ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
$ pg_ctl restart -D /usr/local/var/postgres
$ launchctl load -w ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist


If your datadir is elsewhere you can find out where it is by examining the output of ps aux | grep postgres

artemave
  • 6,786
  • 7
  • 47
  • 71
13
SELECT 
pg_terminate_backend(pid) 
FROM 
pg_stat_activity 
WHERE
pid <> pg_backend_pid()
-- no need to kill connections to other databases
AND datname = current_database();
-- use current_database by opening right query tool
Janki
  • 191
  • 1
  • 8
9

If you need to disconnect sessions of a particular user, this helped me:

Check all current connections:

select * from pg_stat_activity; 

Grant a role to your user (not important):

set role "db_admin";

Kill sessions:

select pg_terminate_backend(pid)
from pg_stat_activity
where usename = '*** USER NAME TO DISCONNECT ***';
eku-code
  • 111
  • 1
  • 4
  • 1
    This is great, just what I needed. The site was down, but my local GUI DB client was still connected! Disconnected that, and I was able to make the change. – Nick K9 Oct 29 '22 at 14:49
8

MacOS, if postgresql was installed with brew:

brew services restart postgresql

UBUNTU,

firstly check with this (kill server which is running in background)

sudo kill -9 $(lsof -i :3000 -t)

if you didn't find pid Then you just need to restart Postgresql service by command which is mention are as under:

sudo service postgresql restart
CHAVDA MEET
  • 777
  • 8
  • 14
8

This seems to be working for PostgreSQL 9.1:

#{Rails.root}/lib/tasks/databases.rake
# monkey patch ActiveRecord to avoid There are n other session(s) using the database.
def drop_database(config)
  case config['adapter']
  when /mysql/
    ActiveRecord::Base.establish_connection(config)
    ActiveRecord::Base.connection.drop_database config['database']
  when /sqlite/
    require 'pathname'
    path = Pathname.new(config['database'])
    file = path.absolute? ? path.to_s : File.join(Rails.root, path)

    FileUtils.rm(file)
  when /postgresql/
    ActiveRecord::Base.establish_connection(config.merge('database' => 'postgres', 'schema_search_path' => 'public'))
    ActiveRecord::Base.connection.select_all("select * from pg_stat_activity order by procpid;").each do |x|
      if config['database'] == x['datname'] && x['current_query'] =~ /<IDLE>/
        ActiveRecord::Base.connection.execute("select pg_terminate_backend(#{x['procpid']})")
      end
    end
    ActiveRecord::Base.connection.drop_database config['database']
  end
end

Lifted from gists found here and here.

Here's a modified version that works for both PostgreSQL 9.1 and 9.2.

Community
  • 1
  • 1
Chris
  • 1,419
  • 14
  • 17
6

I use the following rake task to override the Rails drop_database method.

lib/database.rake

require 'active_record/connection_adapters/postgresql_adapter'
module ActiveRecord
  module ConnectionAdapters
    class PostgreSQLAdapter < AbstractAdapter
      def drop_database(name)
        raise "Nah, I won't drop the production database" if Rails.env.production?
        execute <<-SQL
          UPDATE pg_catalog.pg_database
          SET datallowconn=false WHERE datname='#{name}'
        SQL

        execute <<-SQL
          SELECT pg_terminate_backend(pg_stat_activity.pid)
          FROM pg_stat_activity
          WHERE pg_stat_activity.datname = '#{name}';
        SQL
        execute "DROP DATABASE IF EXISTS #{quote_table_name(name)}"
      end
    end
  end
end

Edit: This is for Postgresql 9.2+

Chris Aitchison
  • 4,656
  • 1
  • 27
  • 43
  • You need to use `pg_stat_activity.procpid` instead of `pg_stat_activity.pid` for Postgres 9.1 and below. See http://stackoverflow.com/a/5408501/444774 – talyric May 09 '13 at 23:44
  • 1
    This is a great answer! It's better and safer than the Rails default. Thanks! – piersadrian Jul 12 '13 at 23:12
5

I'VE SOLVED THIS WAY:

In my Windows8 64 bit, just restarting the service: postgresql-x64-9.5

X-Coder
  • 2,632
  • 2
  • 19
  • 17
  • 6
    That is just doing a restart which is generally not desirable for production environments, killing the hug process is a much more desirable option. – BrianC Apr 01 '17 at 15:54
4

I had this issue and the problem was that Navicat was connected to my local Postgres db. Once I disconnected Navicat the problem disappeared.

EDIT:

Also, as an absolute last resort you can back up your data then run this command:

sudo kill -15 `ps -u postgres -o pid`

... which will kill everything that the postgres user is accessing. Avoid doing this on a production machine but you shouldn't have a problem with a development environment. It is vital that you ensure every postgres process has really terminated before attempting to restart PostgreSQL after this.

EDIT 2:

Due to this unix.SE post I've changed from kill -9 to kill -15.

Community
  • 1
  • 1
Jamon Holmgren
  • 23,738
  • 6
  • 59
  • 75
  • 1
    In my limited experience with Navicat Lite, simply closing the database or server connection is not always enough. Navicat Lite seems to keep the occasional connection open until the application is terminated. – ken Jun 05 '13 at 13:32
3

In PG admin you can disconnect your server (right click on the server) & all sessions will be disconnected at restart

2

Quit postgres and restart it. Simple, but works every time for me, where other cli commands sometimes don't.

Stan Amsellem
  • 503
  • 1
  • 5
  • 16
1

There is no need to drop it. Just delete and recreate the public schema. In most cases this have exactly the same effect.

namespace :db do

desc 'Clear the database'
task :clear_db => :environment do |t,args|
  ActiveRecord::Base.establish_connection
  ActiveRecord::Base.connection.tables.each do |table|
    next if table == 'schema_migrations'
    ActiveRecord::Base.connection.execute("TRUNCATE #{table}")
  end
end

desc 'Delete all tables (but not the database)'
task :drop_schema => :environment do |t,args|
  ActiveRecord::Base.establish_connection
  ActiveRecord::Base.connection.execute("DROP SCHEMA public CASCADE")
  ActiveRecord::Base.connection.execute("CREATE SCHEMA public")
  ActiveRecord::Base.connection.execute("GRANT ALL ON SCHEMA public TO postgres")
  ActiveRecord::Base.connection.execute("GRANT ALL ON SCHEMA public TO public")
  ActiveRecord::Base.connection.execute("COMMENT ON SCHEMA public IS 'standard public schema'")
end

desc 'Recreate the database and seed'
task :redo_db => :environment do |t,args|
  # Executes the dependencies, but only once
  Rake::Task["db:drop_schema"].invoke
  Rake::Task["db:migrate"].invoke
  Rake::Task["db:migrate:status"].invoke 
  Rake::Task["db:structure:dump"].invoke
  Rake::Task["db:seed"].invoke
end

end
jtsagata
  • 2,263
  • 1
  • 13
  • 7
1

Just wanted to point out that Haris's Answer might not work if some other background process is using the database, in my case it was delayed jobs, I did:

script/delayed_job stop

And only then I was able to drop/reset the database.

mlabarca
  • 796
  • 7
  • 16
1

Remote scenario. But if you're trying to run tests in a rails app, and you get something like

"ActiveRecord::StatementInvalid: PG::ObjectInUse: ERROR: database "myapp_test" is being accessed by other users DETAIL: There is 1 other session using the database."

Make sure you close pgAdmin or any other postgres GUI tools before running tests.

Shifa Khan
  • 769
  • 6
  • 12
1

Case :
Fail to execute the query :

DROP TABLE dbo.t_tabelname

Solution :
a. Display query Status Activity as follow :

SELECT * FROM pg_stat_activity  ;

b. Find row where 'Query' column has contains :

'DROP TABLE dbo.t_tabelname'

c. In the same row, get value of 'PID' Column

example : 16409

d. Execute these scripts :

SELECT 
    pg_terminate_backend(25263) 
FROM 
    pg_stat_activity 
WHERE 
    -- don't kill my own connection!
    25263 <> pg_backend_pid()
    -- don't kill the connections to other databases
    AND datname = 'database_name'
    ;
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Fahwi
  • 21
  • 1
1

I'm on a mac and I use postgres via Postgres.app. I solved this problem just quitting and starting again the app.

1

Open PGadmin see if there is any query page open, close all query page and disconnect the PostgresSQL server and Connect it again and try delete/drop option.This helped me.

1

Definitely one of the answers above gave me the idea for solving it in Windows.

Open the Services from Windows, locate the Postgres service and restart it.

Jesús Vera
  • 321
  • 2
  • 5
1

First, locate the PID of the query/connection you want to close (see How to list active connections on PostgreSQL?)

mydb=> select pid, application_name, state, query from pg_stat_activity where application_name = 'myapp';
 pid  | application_name | state | query 
------+------------------+-------+-------
 1234 | myapp            | idle  | 
 5678 | myapp            | idle  | 
(2 rows)

Then, closing the connection with the PID you picked like this

mydb=> SELECT pg_terminate_backend(1234);
bachr
  • 5,780
  • 12
  • 57
  • 92
-1

For me worked the following:

sudo gitlab-ctl stop
sudo gitlab-ctl start gitaly
sudo gitlab-rake gitlab:setup [type yes and let it finish]
sudo gitlab-ctl start

I am using:
gitlab_edition: "gitlab-ce"
gitlab_version: '12.4.0-ce.0.el7'

Kostas Demiris
  • 3,415
  • 8
  • 47
  • 85
-5

the answer is hidden in one of the comments above: brew services restart postgresql

Thomas Van Holder
  • 1,137
  • 9
  • 12