385

Is there a command in PostgreSQL to select active connections to a given database?

psql states that I can't drop one of my databases because there are active connections to it, so I would like to see what the connections are (and from which machines)

ivanleoncz
  • 9,070
  • 7
  • 57
  • 49
Tregoreg
  • 18,872
  • 15
  • 48
  • 69
  • 3
    Possible duplicate of [How can you get the active users connected to a postgreSQL database via SQL?](http://stackoverflow.com/questions/464623/how-can-you-get-the-active-users-connected-to-a-postgresql-database-via-sql) – Brad Koch Aug 09 '16 at 14:57
  • Great! i search (badly) and don't found anything. Can i do something to close others idle connection? – Speaker May 23 '20 at 22:50

5 Answers5

687

Oh, I just found that command on PostgreSQL forum:

SELECT * FROM pg_stat_activity;
Tregoreg
  • 18,872
  • 15
  • 48
  • 69
93

Following will give you active connections/ queries in postgres DB-

SELECT 
    pid
    ,datname
    ,usename
    ,application_name
    ,client_hostname
    ,client_port
    ,backend_start
    ,query_start
    ,query
    ,state
FROM pg_stat_activity
WHERE state = 'active';

You may use 'idle' instead of active to get already executed connections/queries.

pdoherty926
  • 9,895
  • 4
  • 37
  • 68
Neeraj Bansal
  • 2,580
  • 16
  • 8
  • 2
    Does idle means connection is active?. If I m releasing connection, still will it be listed as idle? – Shivam Kubde Aug 21 '19 at 12:31
  • 2
    Yes @ShivamKubde but as 'idle', and the query above only show 'active' connections, so remove the `WHERE ...` clause and to be able to see what connections are active or idle add the column `state` to the `SELECT` clause – Mariano Ruiz Jan 29 '20 at 20:20
  • @ReneChan it is due to too many connections to your database. Normally the maximum is 100. You must have created more than that. – Anandakrishnan Nov 07 '22 at 18:06
42
SELECT * FROM pg_stat_activity WHERE datname = 'dbname' and state = 'active';

Since pg_stat_activity contains connection statistics of all databases having any state, either idle or active, database name and connection state should be included in the query to get the desired output.

Abdollah
  • 4,579
  • 3
  • 29
  • 49
11

You can check connection details in Postgres using pg_stat_activity. You can apply filter to satisfy your condition. Below are queries. References: https://orahow.com/check-active-connections-in-postgresql/

SELECT * FROM pg_stat_activity WHERE state = 'active';
select * from pg_stat_activity where state = 'active' and datname = 'REPLACE_DB_NAME_HERE';
santosh tiwary
  • 598
  • 6
  • 4
11

If you would like to use PgAdmin (for me it is more than convenient), you could do these simple steps. Glad if this is helps

SELECT * FROM pg_stat_activity;

example

Igor S.
  • 301
  • 3
  • 7