diff --git a/README.md b/README.md index a7edee1..3caba80 100644 --- a/README.md +++ b/README.md @@ -175,6 +175,7 @@ _340 TILs and counting..._ - [List All Rows In A Table](postgres/list-all-rows-in-a-table.md) - [List All Versions Of A Function](postgres/list-all-versions-of-a-function.md) - [List Available Schemas](postgres/list-available-schemas.md) +- [List Connections To A Database](postgres/list-connections-to-a-database.md) - [List Database Users](postgres/list-database-users.md) - [Max Identifier Length Is 63 Bytes](postgres/max-identifier-length-is-63-bytes.md) - [pg Prefix Is Reserved For System Schemas](postgres/pg-prefix-is-reserved-for-system-schemas.md) diff --git a/postgres/list-connections-to-a-database.md b/postgres/list-connections-to-a-database.md new file mode 100644 index 0000000..469f22c --- /dev/null +++ b/postgres/list-connections-to-a-database.md @@ -0,0 +1,34 @@ +# List Connections To A Database + +The `pg_stat_activity` table can be used to determine what connections there +currently are to the PostgreSQL server and to a particular database. To see +the process ids and usernames of all connection to your PostgreSQL server, +run the following query: + +```sql +> select pid, usename from pg_stat_activity; + pid | usename +-------+------------ + 57174 | jbranchaud + 83420 | jbranchaud +``` + +Include `datname` in the requested columns to figure out the database of +each connection. + +```sql +> select pid, usename, datname from pg_stat_activity; + pid | usename | datname +-------+------------+----------- + 57174 | jbranchaud | hr_hotels + 83420 | jbranchaud | pgbyex +``` + +The results can be restricted to a particular database as necessary. + +```sql +> select pid, usename from pg_stat_activity where datname = 'hr_hotels'; + pid | usename +-------+------------ + 57174 | jbranchaud +```