connections
POSTGRESQL

How To Kill All Connections to a Database in PostgreSQL

intro

Follow this tutorial and learn how to kill all connections in a PostgreSQL server through different approaches!

Tools used in the tutorial
Tool Description Link
Dbvisualizer DBVISUALIZER
TOP RATED DATABASE MANAGEMENT TOOL AND SQL CLIENT

Situations where you have to terminate the active connections to a database are common in the life of every DBA. For example, that is required to rename or drop a database. To perform such operations, you first have to kill all connections. Similarly, you may need to close all client sessions except for yours.

In this guide, you will dig into the process of closing active connections in PostgreSQL, exploring use cases and different approaches.

Let’s dive in!

What Does It Mean to Kill a PostgreSQL Database Connection?

Killing a PostgreSQL database connection means forcefully terminating an active session connected to the database. Each connection consumes server resources, so this action is useful for resolving conflicts, stopping problematic queries, and reducing server load.

When a connection is killed, any ongoing transactions are rolled back, and the session is closed, freeing up resources and preventing potential issues.

Kill All Connections to a PostgreSQL Database: Use Cases and Scenarios

In PostgreSQL, killing all connections refers to terminating all active sessions established by clients to a database. Here are some scenarios where this operation may be required:

  • Dropping a database: To perform a DROP DATABASE query on a PostgreSQL database, you must ensure that there are no active connections referred to it. Otherwise, the operation would result in the error database "db_name" is being accessed by other users.
  • Renaming a database: Similar to dropping a database, renaming a PostgreSQL database with an ALTER DATABASE query requires terminating all active sessions related to it. Speaking of the rename operation, check out our guide on how to rename a table in MySQL.
  • Testing the environment: When you want to test special conditions or situations, it can be useful to reset the state of the database by clearing all connections. This way, each test will start from a clean starting point. For instance, that is especially useful in the case of a stress test.
  • Emergency situations: In critical scenarios such as security vulnerabilities, data corruption, or severe performance issues, immediately closing all connections can prevent further damage or unauthorized access. If something goes wrong, you can always restore your PostgreSQL databases with pg_restore.
  • Refreshing database configurations: If you update PostgreSQL settings that require a reconnection to take effect (e.g., authentication settings in pg_hba.conf or parameter changes in postgresql.conf), closing all sessions is key to make sure that the new settings are applied.
  • Switching the default tablespace: When moving database objects to a new tablespace, active connections might lock certain objects. That prevents the operation from completing successfully.
  • Freeing up system resources: In high-load environments, a large number of idle or long-running connections can consume system resources. Closing unused sessions helps optimize performance.
  • Handling connection leaks: If an application fails to properly close database connections, terminating them manually can prevent connection exhaustion and improve stability.
  • Database maintenance: Before performing maintenance tasks like schema changes, upgrades, or data migrations, you need to ensure that no active connections will interfere with the process. Removing all sessions enables you to safely execute those tasks without interruptions.

Time to see how to kill connections in Postgres!

Insights Into the pg_stat_activity View

Before seeing how to drop connections to a database in a PostgreSQL server, you need to learn more about the pg_stat_activity view.

pg_stat_activity is a PostgreSQL system view that stores a row for each process running on the DBMS server. In detail, it contains useful information about the current activity of each process:

Retrieving all PostgreSQL backend process info in DbVisualizer
Retrieving all PostgreSQL backend process info in DbVisualizer

The most important columns to focus your attention on are:

  • pid: The ID of the process running on the database server.
  • datname: The name of the database the process is connected to.
  • state: The current state of the process. The possible values are: active, idle, idle in transaction, idle in transaction (aborted), fastpath function call, and disabled.
  • query: The text of the most recent query executed by the process.
  • leader_pid: The ID of the parallel group leader or apply worker. When NULL, it means that the current process is a parallel group leader or apply worker, or it does not participate in any parallel operation.
  • application_name: The name of the client application the connection process refers to.

You are ready to use this view to kill all connections to a Postgres database. If you want to list PostgreSQL databases instead, read our guide.

pg_stat_activity: Column Table

These are all the columns contained in the pg_stat_activity system view:

ColumnData TypeDescription
datidoidOID of the database this backend is connected to
datnamenameName of the connected database
pidintegerProcess ID of this backend
leader_pidintegerProcess ID of the parallel group leader or leader apply worker. NULL if the process is not in a parallel operation
usesysidoidOID of the user logged into this backend
usenamenameName of the user logged into this backend
application_nametextName of the application connected to this backend
client_addrinetIP address of the connected client. NULL for Unix socket connections or internal processes
client_hostnametextHostname of the client (resolved via reverse DNS). Only available for IP connections when log_hostname is enabled
client_portintegerTCP port used by the client, or -1 if using a Unix socket. NULL for internal processes
backend_starttimestamp with time zoneTimestamp when the backend process started (i.e., when the client connected)
xact_starttimestamp with time zoneTimestamp when the current transaction started, or NULL if no transaction is active
query_starttimestamp with time zoneTimestamp when the currently active query (or last executed query) started
state_changetimestamp with time zoneTimestamp when the backend state was last changed
wait_event_typetextType of event the backend is waiting for (if any)
wait_eventtextSpecific event name the backend is waiting on (if any)
statetextCurrent state of the backend: active, idle, idle in transaction, idle in transaction (aborted), fastpath function call, or disabled
backend_xidxidTop-level transaction ID of this backend, if any
backend_xminxidThe backend’s xmin horizon, used for tracking transaction visibility
query_idbigintIdentifier of the most recent query. Only available if compute_query_id is enabled
querytextText of the backend’s most recent query (truncated by default at 1024 bytes, configurable via track_activity_query_size)
backend_typetextType of backend process, such as autovacuum worker, logical replication worker, client backend, walwriter, etc. Extension-defined background workers may have additional types

If you are not familiar with some of the types mentioned above, discover all PostgreSQL data types.

Dropping All Connections to a PostgreSQL Database

To kill all active connections to a PostgreSQL database, execute the query below:

Copy
        
1 SELECT pg_terminate_backend(pid) 2 FROM pg_stat_activity 3 WHERE datname = 'TARGET_DB_NAME' AND leader_pid IS NULL;

Replace TARGET_DB_NAME with the name of the database you want to close sessions for.

Note that the IS NULL condition on leader_pid in the WHERE clause is an optimization to avoid sending too many kill signals. The reason is that, by killing the parent process, parallel workers will die as a result. So, you can ignore processes associated with parallel workers by forcing the IS NULL condition.

pg_terminate_backend() is a special administration function that sends the SIGINT or SIGTERM signal to the backend process identified by the ID passed as a parameter. In other words, it kills processes on the database server based on their ID.

Warning: The above query will also terminate all the queries running on the specified database. That is because each PostgreSQL backend process is typically responsible for maintaining a connection for a client or executing a single query. So, when the process is terminated, the query associated with that process is stopped. In particular, any transaction associated with that process is rolled back.

If you want to kill only active connections, enforce the state = 'active' condition:

Copy
        
1 SELECT pg_terminate_backend(pid) 2 FROM pg_stat_activity 3 WHERE datname = 'TARGET_DB_NAME' AND leader_pid IS NULL AND state = 'active';

Keep in mind that only users with a SUPERUSER role can run these operations. That reason is that these queries should be used sparingly and only when truly required.

Terminate All Queries but Keep Connections Alive

If you want to terminate a process–such as a query—but keep the connection alive, use pg_cancel_backend():

Copy
        
1 SELECT pg_cancel_backend(pid) 2 FROM pg_stat_activity 3 WHERE datname = 'TARGET_DB_NAME' AND leader_pid IS NULL;

Remember that an app connected to the database can recover from a failed query, but if the session is closed, it will need to open a new cursor to re-establish the connection and continue operations.

Killing All Connections in PostgreSQL: Complete Example

Try to launch the query for closing all PostgreSQL connections and you will get a similar result:

Note the two true records in the result set. It means that two processes have been terminated.
Note the two true records in the result set. It means that two processes have been terminated.

As you can see, the two connections to the games database have been terminated. Be sure to run that query from a database connection that is not in TARGET_DB_NAME. Otherwise, the operation will fail with the error message below:

Copy
        
1 1) [Code: 0, SQL State: 57P01] FATAL: terminating connection due to administrator command 2 2) [Code: 0, SQL State: 08006] An I/O error occurred while sending to the backend.
Executing the query in DbVisualizer with a connection to the target database
Executing the query in DbVisualizer with a connection to the target database

To avoid that, you can modify the query to kill all connections except for yours, as below:

Copy
        
1 SELECT pg_terminate_backend(pid) 2 FROM pg_stat_activity 3 WHERE datname = 'TARGET_DB_NAME' AND pid != pg_backend_pid() AND leader_pid IS NULL;

pg_backend_pid() is a system information function that returns the process ID of the current session.

This time, you will achieve the target outcome with no errors:

Running the query in DbVisualizer
Running the query in DbVisualizer

Et voilà! You know now how to terminate connections in PostgreSQL.

Conclusion

In this article, you learned what it means to kill a connection to a database in a PostgreSQL server. In detail, killing all connections is a powerful technique required in several scenarios, including dropping or renaming a database and ensuring a clean environment for testing. By following the instructions provided here, you learned how to safely terminate connections and proceed with your database operations.

Managing database connections can easily become a complex task. This is where a feature-rich database client with full PostgreSQL support such as DbVisualizer comes in. From the same tool, you can connect to dozens of database technologies, visually explore their table structure, optimize queries, and generate ERD-like schemas with a single click. Download DbVisualizer for free today!

FAQ

How to get the list of active connections in PostgreSQL?

You can retrieve the list of active connections in PostgreSQL by executing the SQL query below:

Copy
        
1 SELECT * FROM pg_stat_activity;

This provides information about the current connections, including their process IDs (PIDs) and associated details.

How to kill all connections in PostgreSQL?

To terminate all connections to all databases in a Postgres server, run the following query:

Copy
        
1 SELECT pg_terminate_backend(pid) 2 FROM pg_stat_activity 3 WHERE pid != pg_backend_pid() 4 AND datname IS NOT NULL AND leader_pid IS NULL;

In older PostgreSQL versions, pg_stat_activity only covered database connections. In newer versions, it also includes information about various processes unrelated to a specific database, like background writers and parallel workers. Excluding datname rows with NULL values ensures that you are killing only database-related processes.

What are the privileges or permissions required to kill processes in PostgreSQL?

To kill processes in PostgreSQL, you need to connect to the database with the postgres admin account or an account with SUPERUSER role. These are the users that have the necessary privileges to terminate processes.

How to kill/stop a query in PostgreSQL?

First, check the running processes by executing:

Copy
        
1 SELECT * FROM pg_stat_activity 2 WHERE state = 'active';

Find the PID (<pid_of_the_process>) of the process you want to kill. Then, you have two options:

Option #1: Launch the query below to initiate a request to terminate the query gracefully, which may take some time to complete, though the query will return immediately:

Copy
        
1 SELECT pg_cancel_backend(<pid_of_the_process>);

Option #2: Execute this query to forcefully terminate the backend process:

Copy
        
1 SELECT pg_terminate_backend(<pid of the process>);

How to rename a database in PostgreSQL?

To rename a database in PostgreSQL, you can use the ALTER DATABASE statement followed by the RENAME TO clause. For example, to rename a table from "old_name" to "new_name", execute:

Copy
        
1 ALTER TABLE old_name RENAME TO new_name;

Does pg_terminate_backend() drop connections together or one by one?

pg_terminate_backend() terminates connections individually. If you feed the command with the PIDs from pg_stat_activity as explained in this article, it will be executed for each active connection, one at a time.

What happens to active transactions when all connections to a PostgreSQL database are terminated?

When all connections to a PostgreSQL database are terminated, any active transactions are rolled back. This ensures data integrity and prevents any partial or inconsistent updates from being committed.

How to kill all other active connections to your database in PostgreSQL?

To terminate all other database connections to the db_name Postgres database except for yours, run:

Copy
        
1 SELECT pg_terminate_backend(pg_stat_activity.pid) 2 FROM pg_stat_activity 3 WHERE pg_stat_activity.datname = 'db_name' AND pid != pg_backend_pid() AND leader_pid IS NULL;

Or, equivalently, execute:

Copy
        
1 SELECT pg_terminate_backend(pid) 2 FROM pg_stat_get_activity(NULL::integer) 3 WHERE datid = ( 4 SELECT oid 5 FROM pg_database 6 WHERE datname = 'db_name' 7 ) AND pid != pg_backend_pid() AND leader_pid IS NULL;

The second query uses an SQL subquery. Find out more about that mechanism in our guide on SQL subqueries.

What is the difference between pg_cancel_backend() and pg_terminate_backend()?

The difference between pg_cancel_backend() and pg_terminate_backend() in PostgreSQL is that pg_cancel_backend() attempts to cancel an active process (such as a long query) without terminating the connection, allowing the session to continue. In contrast, pg_terminate_backend() forcefully ends the entire session, terminating the connection and rolling back any ongoing transactions. So, pg_cancel_backend()may take some time to complete, returning true in case of a gaceful cleanup. On the other hand, pg_terminate_backend() acts like a "hard kill," forcibly terminating the backend process without waiting for cleanup.

Dbvis download link img
About the author
Antonello Zanini

Antonello is a software engineer, and often refers to himself as a technology bishop. His mission is to spread knowledge through writing.

The Table Icon
Sign up to receive The Table's roundup
More from the table
Title Author Tags Length Published
title

PostgreSQL Truncate Table Reset Sequence Guide

author Antonello Zanini tags POSTGRESQL 6 min 2025-02-17
title

Clustered vs Non-Clustered Index: Complete SQL Guide

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 8 min 2025-02-13
title

Queries and Subqueries in SQL: The Definitive Guide

author Lukas Vileikis tags DbVisualizer MySQL POSTGRESQL SQL SQL SERVER 7 min 2025-02-12
title

SQL Derived Table: Everything You Need to Know

author Antonello Zanini tags MySQL POSTGRESQL SQL SQL SERVER 9 min 2025-02-06
title

How To List Databases in PostgreSQL: A Complete Guide

author Antonello Zanini tags POSTGRESQL 8 min 2025-02-05
title

Postgres Create Array of Numbers: Complete Guide

author Lukas Vileikis tags POSTGRESQL SQL 7 min 2025-02-03
title

A Complete Guide to the ALTER TABLE DROP COLUMN Statement

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 8 min 2025-01-27
title

All You Need to Know About PostgreSQL UNIQUE Constraint

author Leslie S. Gyamfi tags POSTGRESQL 7 min 2025-01-23
title

How to Use a Recursive CTE in SQL

author Antonello Zanini tags MySQL POSTGRESQL SQL SQL SERVER 5 min 2025-01-22
title

How to Use MERGE in SQL Query Statements: Complete Guide

author Antonello Zanini tags ORACLE POSTGRESQL SQL SQL SERVER 8 min 2025-01-20

The content provided on dbvis.com/thetable, including but not limited to code and examples, is intended for educational and informational purposes only. We do not make any warranties or representations of any kind. Read more here.