How to Cancel a Query or Terminate a Session in PostgreSQL

PostgreSQL · Session intervention · DBA-017

How to Cancel a Query or Terminate a Session in PostgreSQL

Identify the exact backend, cancel the current statement first, and escalate to disconnecting a session only when necessary.

The short answer

Use pg_cancel_backend(pid) to request cancellation of a running statement while keeping its connection. If the underlying session remains harmful—such as an idle transaction holding locks—pg_terminate_backend(pid) disconnects it and causes its open transaction to roll back. Confirm the correct PID immediately before either action.

Step 1: identify the exact session

Begin with a read-only inspection of active connections. Match the application, user, query text, state and backend start time. Never select a PID from an old screenshot or an earlier incident.

Read-only · identify a backend before intervention
SELECT
    pid,
    usename,
    datname,
    application_name,
    client_addr,
    state,
    backend_start,
    xact_start,
    wait_event_type,
    wait_event,
    left(query, 160) AS query_preview
FROM pg_stat_activity
WHERE backend_type = 'client backend'
  AND pid <> pg_backend_pid()
ORDER BY xact_start NULLS LAST, query_start NULLS LAST
LIMIT 50;

The query excludes your own backend; visibility of other users’ SQL can depend on monitoring privileges.

Step 2: cancel before terminating

After confirming the specific PID and getting any required operational approval, request cancellation. The command below is deliberately commented out so copying the diagnostic query cannot accidentally signal a real backend.

Intervention template · replace 12345 with the freshly verified PID
-- Uncomment only after confirming the correct target PID.
-- SELECT pg_cancel_backend(12345);

-- Escalate only if cancellation is insufficient and the
-- connection itself must be ended.
-- SELECT pg_terminate_backend(12345);

Cancellation stops the current statement if it is still running. Termination ends the connection; an in-progress transaction is rolled back. A return value of true normally means that PostgreSQL successfully sent the signal—not necessarily that work has already stopped.

How to decide whether to escalate

pg_cancel_backendFirst choice for an expensive or runaway statement when the session can remain connected.
pg_terminate_backendLast-resort session removal, including an idle-in-transaction blocker or a session that will not stop.
backend_startHelps verify a PID refers to the same session you inspected, because operating-system PIDs can be reused.
state / xact_startSeparates an actively executing query from an open transaction that may still retain locks.

Inspect the target again after the signal. If the session disappears and immediately returns, the application or connection pool may be retrying the same work.

A safer intervention sequence

  1. Identify the impact. Establish whether the session is blocking others, exhausting resources or simply doing expected long-running work.
  2. Check ownership and application context. Know which workload will be interrupted.
  3. Confirm the PID again. Session identifiers can change between diagnosis and action.
  4. Try cancel first. Allow the application a chance to handle the statement error.
  5. Escalate only with intent. Termination disconnects the client and may trigger a costly rollback.
  6. Verify recovery. Recheck pg_stat_activity and blockers; investigate recurring queries at the application layer.

Related DBA tasks

DBA-015 (active sessions), DBA-016 (long-running work), DBA-018 (blocking chains), and DBA-020 (connection pressure) provide the context needed to decide whether intervention is warranted.

Continue learning · Baldwin Apps

More practical solutions in SQL Recipes for DBAs

Find engine-specific recipes for sessions, locks, performance, permissions, backups, maintenance, and troubleshooting. Explore the book and its existing companion materials.

Published

Leave a comment

Your email address will not be published. Required fields are marked *