🧚 Atenção! Beekeeper Studio é uma GUI de banco de dados rápida, moderna e de código aberto Download
July 17, 2024 Por Matthew Rathbone

You can terminate a problematic session using the pg_terminate_backend function.

SELECT pg_terminate_backend(PID);

Identifying Long-Running Queries

Before terminating a session in PostgreSQL, you need to know which session to target. To find long-running queries, you can use the pg_stat_activity view and filter by the state and query_start columns.

SELECT pid, usename, state, query, now() - query_start AS duration
FROM pg_stat_activity
WHERE state = 'active'
ORDER BY duration DESC;

Expected Output:

pid usename state query duration
1236 appuser active UPDATE orders SET status=’paid’; 00:20:34
1234 postgres active SELECT * FROM users; 00:05:12

Terminating a Session

Once you have identified the problematic session, you can terminate it using the pg_terminate_backend function.

SELECT pg_terminate_backend(1236);

This command forcibly terminaties the connection to the backend. It sends a SIGTERM signal to the process and allows it to terminate safely, offering a final chance to clean up before it terminates. Before executing this command, make sure to check the nature of the running queries and consider the output.

Automating Session Termination

For environments where session issues are frequent, you can automate session termination using a script. Here is an example of a basic script to terminate long-running queries:

DO $$ 
DECLARE
    r RECORD;
BEGIN
    FOR r IN
        SELECT pid 
        FROM pg_stat_activity 
        WHERE state = 'active' 
        AND now() - query_start > interval '10 minutes'
    LOOP
        PERFORM pg_terminate_backend(r.pid);
    END LOOP;
END $$;

This script will terminate any active session that has been running for more than 10 minutes.

Using the pg_cancel_backend function

Sometimes, it’s not desirable to kill a session but to simply cancel the query that the session is executing. In such cases, you can use the pg_cancel_backend function.

SELECT pg_cancel_backend(PID);

Replace PID with the process ID of the session with the query you want to cancel.

This command sends a SIGINT to the process to cancel the query. It’s less brute force compared to pg_terminate_backend, and allows the session itself to remain alive, even though the running query gets cancelled.

Remember, that both pg_cancel_backend and pg_terminate_backend have the superuser access requirement. If the session you are trying to terminate or cancel belongs to a superuser, you will need superuser privileges to run these commands successfully.

Conclusion

You now know how to kill sessions in PostgreSQL. Managing sessions in PostgreSQL is an important skill for database administrators. By effectively identifying and terminating problematic sessions, you can better maintain the performance and reliability of your PostgreSQL databases. Remember to use these commands judiciously, as their misuse can interrupt important data processing steps and compromise the integrity of your PostgreSQL databases.

Other posts you might enjoy:

Beekeeper Studio É Uma GUI de Banco de Dados Gratuita e de Código Aberto

A melhor ferramenta de consultas SQL e editor que já usei. Fornece tudo que preciso para gerenciar meu banco de dados. - ⭐⭐⭐⭐⭐ Mit

Beekeeper Studio é rápido, intuitivo e fácil de usar. Beekeeper suporta muitos bancos de dados e funciona muito bem no Windows, Mac e Linux.

A versão Linux do Beekeeper é 100% completa, sem cortes e sem compromissos de recursos.

O Que Os Usuários Dizem Sobre o Beekeeper Studio

★★★★★
"O Beekeeper Studio substituiu completamente meu antigo fluxo de trabalho com SQL. É rápido, intuitivo e torna o trabalho com banco de dados agradável novamente."
— Alex K., Desenvolvedor de Banco de Dados
★★★★★
"Já experimentei muitas GUIs de banco de dados, mas o Beekeeper encontra o equilíbrio perfeito entre recursos e simplicidade. Simplesmente funciona."
— Sarah M., Engenheira Full Stack

Pronto para Melhorar seu Fluxo de Trabalho com SQL?

download Download Gratuito