How to list active connections on PostgreSQL?

2020-05-12 02:37发布

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)

3条回答
The star\"
2楼-- · 2020-05-12 03:02

Oh, I just found that command on PostgreSQL forum:

SELECT * FROM pg_stat_activity;
查看更多
太酷不给撩
3楼-- · 2020-05-12 03:23

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.

查看更多
一夜七次
4楼-- · 2020-05-12 03:25
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.

查看更多
登录 后发表回答