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 in a PostgreSQL Server: Use Cases

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.
  • 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.

Dropping All Active 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.

Warning: The above query will also terminate all the queries running on the specified database.

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.  

Note: Use pg_cancel_backend() if you want to terminate a process–such as a query–but keep the connection alive.

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.

Keep in mind that only users with a SUPERUSER role can run this operation. This is because it is a solution that should be used sparingly and only when truly required.

Try to launch the query for closing 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 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.

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

A Guide To the SQL DECLARE Statement

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SERVER 7 min 2024-12-12
title

SQL Upsert: Inserting a Record If It Does Not Exist

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 8 min 2024-12-10
title

How to Find Elements In an Array: PostgreSQL Guide

author Antonello Zanini tags POSTGRESQL 3 min 2024-12-05
title

How and Why to Add an Index in SQL

author Lukas Vileikis tags MySQL POSTGRESQL Search SQL SQL SERVER 8 min 2024-11-28
title

Postgres Create Array of Numbers: Complete Guide

author Lukas Vileikis tags POSTGRESQL SQL 7 min 2024-11-21
title

List of SQL Reserved Words in All Major Databases

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 16 min 2024-11-20
title

SQL Variable: What It Is and How To Use It

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 8 min 2024-11-18
title

Postgres DATEDIFF Equivalent Functions: Calculating Date and Time Differences

author Lukas Vileikis tags POSTGRESQL 6 min 2024-11-04
title

CREATE SCHEMA PostgreSQL Statement: What, Why & When to Use

author Lukas Vileikis tags POSTGRESQL 4 min 2024-10-30
title

SQL EXPLAIN: The Definitive Tool to Optimize Queries

author Antonello Zanini tags MySQL POSTGRESQL SQL 12 min 2024-10-29

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.

Cookie policy

We use cookies to ensure that we give you the best experience on our website. However you can change your cookie settings at any time in your browser settings. Please find our cookie policy here ↗