Terminate a database connection by process ID
Destructive
What do risk levels mean?
- Read-only
- Inspects state without changing anything.
- Low risk
- Reversible with a routine follow-up command.
- Medium risk
- Changes state; undo path documented.
- Destructive
- Deletes or overwrites; confirmation required.
Forcefully closes a specific backend process, freeing locks and resources held by a stuck or idle session.
postgresqlconnectionsterminateadministration
Confirmation required
This recipe is destructive and requires confirmation — confirm you understand the impact before running any command below.
Parameters
Process ID of the backend to terminate, found via pg_stat_activity.
Commands
Confirm which connection will be terminated
psql -c "SELECT pid, usename, datname, application_name, state, query FROM pg_stat_activity WHERE pid = <pid>;"Terminate the identified backend process
psql -c "SELECT pg_terminate_backend(<pid>);"Verification
psql -c "SELECT pid FROM pg_stat_activity WHERE pid = <pid>;"No rows returned — the connection has been terminated.
Undo
Not undoable
A terminated connection and its in-flight transaction cannot be restarted. The client application must reconnect and retry any incomplete work.
Pitfalls
- Terminating a connection rolls back any open transaction; data changes in that transaction are lost.
- Only superusers or the connection owner can terminate a backend.
- The pg_stat_activity view refreshes asynchronously; a brief delay may be visible after termination.
- Be careful not to terminate your own psql session; the recipe verifies the target first.