Cancel a long-running query in PostgreSQL
pg_cancel_backend stops the running statement and leaves the connection up. Here is how to pick the target and what happens to its transaction.
The task
PostgreSQL has two ways to stop someone else's work. pg_cancel_backend(pid) aborts the running statement and leaves the connection open. pg_terminate_backend(pid) ends the connection and rolls back its transaction. Cancel first: it is usually enough, and the application gets an ordinary query error instead of a dropped connection. Cancelling still throws away what the statement did, because the statement's changes roll back.
The snippet
Written for PostgreSQL. Versions for SQL Server are under Variations.
SELECT pid, usename, datname, state,
now() - query_start AS runtime,
LEFT(query, 120) AS query,
wait_event_type, wait_event,
pg_cancel_backend(pid) AS cancel_requested
FROM pg_stat_activity
WHERE state = 'active'
AND backend_type = 'client backend'
AND now() - query_start > interval '5 minutes'
AND pid <> pg_backend_pid()
ORDER BY query_start;
How it works
As written, this cancels every client statement that has run for more than five minutes, so run it without the pg_cancel_backend column first and look at the list. The checks: leave out your own session (pid <> pg_backend_pid()); look at wait_event_type, because a query waiting on a Lock is a victim and cancelling it frees nothing; ask the owner before cancelling a batch job or import; and expect the effect on the transaction. Outside an explicit transaction the statement simply rolls back. Inside BEGIN ... COMMIT, the whole transaction is now aborted: the session shows idle in transaction (aborted), keeps its locks, and rejects every statement until the client sends ROLLBACK. A cancel can also be ignored for a while by code that does not check for interrupts. In either case pg_terminate_backend is the next step.
Variations
Cancel by explicit pid (the usual one-off case)
SELECT pg_cancel_backend(12345);
SQL Server: KILL ends the whole session
SQL Server-- SQL Server has no cancel-statement-only command for another session;
-- KILL disconnects it and rolls back its open transaction.
KILL 53;
Questions that come up
I cancelled the query but the session still holds locks. Why?
Because the statement ran inside an explicit transaction. Cancelling aborted that transaction but did not end it: the session is idle in transaction (aborted) and keeps its locks until the application issues ROLLBACK. If the application never does, pg_terminate_backend ends the connection, which rolls the transaction back and releases the locks.
How do I stop spending every incident hand-killing queries?
Set statement_timeout per role, with a short limit for the application role and a longer one for reporting and batch roles, and set lock_timeout in migration sessions. The statement-timeout recipe shows both. A timeout also leaves a clear trace: the client gets ERROR: canceling statement due to statement timeout, and the same line goes to the server log.
Keep reading
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.