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는 무료 & 오픈 소스 데이터베이스 GUI입니다
제가 사용해 본 최고의 SQL 쿼리 & 편집기 도구입니다. 데이터베이스 관리에 필요한 모든 것을 제공합니다. - ⭐⭐⭐⭐⭐ Mit
Beekeeper Studio는 빠르고 직관적이며 사용하기 쉽습니다. Beekeeper는 많은 데이터베이스를 지원하며 Windows, Mac, Linux에서 훌륭하게 작동합니다.
사용자들이 Beekeeper Studio에 대해 말하는 것
"Beekeeper Studio는 제 예전 SQL 워크플로를 완전히 대체했습니다. 빠르고 직관적이며 데이터베이스 작업을 다시 즐겁게 만들어 줍니다."
"많은 데이터베이스 GUI를 사용해 봤지만, Beekeeper는 기능과 단순함 사이의 완벽한 균형을 찾았습니다. 그냥 작동합니다."