Sometimes we need to terminate active connections to a database forcefully. Doing such requires two things, determining which active connections to target and running the command to terminate them. This post shows how to terminate active connections using some SQL commands, and we tested PostgreSQL 10.5.
Which PostgreSQL Connections To Target
Before we terminate some PostgreSQL active connections, we need to identify which ones to target. We can do it by running queries against PostgreSQL using some system tables. One table is pg_stat_activity. Consider the following codes.
1 | SELECT pid, application_name, client_addr FROM pg_stat_activity; |
When we run the codes, we get the following results on our machine.
1 2 3 4 5 6 7 8 9 10 11 | +---+-----------------+-----------+----------+ |pid|application_name |client_addr|usename | +---+-----------------+-----------+----------+ |45 | |NULL |NULL | |46 | |NULL |turreta | |58 |DataGrip 2021.1.3|172.23.0.1 |turreta_sa| |62 |DataGrip 2021.1.3|172.23.0.1 |turreta | |26 | |NULL |NULL | |25 | |NULL |NULL | |27 | |NULL |NULL | +---+-----------------+-----------+----------+ |
Note that we need to use a superuser to invoke the SELECT statement. Otherwise, we will get the following error.
1 2 | [57P01] FATAL: terminating connection due to administrator command [08006] An I/O error occurred while sending to the backend. An I/O error occurred while sending to the backend. |
To create a superuser, please read this post. Once we created a superuser, sign in with the new credentials via SQL IDEs to run SQL commands.
Terminate Active Connections
From a list of rows emanating from the pg_stat_activity table, we can choose which connections to target. Then, we can use a PostgreSQL stored procedure pg_terminate_backend.
1 | SELECT pg_terminate_backend(pid) |
The pid field refers to the column in the pg_terminate_backend table. We can also terminate PostgreSQL active connections belonging to a particular user. Consider the following sample SQL statement.
1 2 3 | SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE usename = 'another_dbuser'; |