Skip to content

Cancel or kill a query in PostgreSQL

Use pg_cancel_backend to stop a session’s current query, or pg_terminate_backend to disconnect the session. First identify the target in the current database:

SELECT pid, usename, state, query_start, xact_start, query
FROM pg_stat_activity
WHERE datname = current_database()
AND pid <> pg_backend_pid()
ORDER BY query_start;

Check the user, query, and transaction before acting. Replace 12345 with the intended PID and run only the command you need.

SELECT pg_cancel_backend(12345);

Cancellation leaves the session connected. Its owner may need to roll back an explicit transaction after the query fails. To end the entire session instead:

SELECT pg_terminate_backend(12345);

Get the session owner’s approval before termination. PostgreSQL disconnects the client and rolls back its uncommitted transaction. For these one-argument calls, true means the signal was sent; check activity again to confirm the outcome. See PostgreSQL’s signaling reference.

Cancel or kill a query in PostgreSQL with TableAI

Section titled “Cancel or kill a query in PostgreSQL with TableAI”

For the query running in your editor, choose Query › Cancel Query, ⌘.. The SQL workflow explains editor cancellation.

For another session:

  1. Open Admin › Connections.
  2. Select the target session.
  3. Choose Cancel Query, or Kill Connection to disconnect it.
  4. Review the target in the confirmation dialog.
  5. Complete the required confirmation.
  6. Check the session list again.

Available actions depend on your database privileges and connection’s query protection rules. See query guardrails for those rules.

Connections with a selected demo session and Cancel Query action

No extension is required. You can signal sessions of roles your role is permitted to control. pg_signal_backend permits signaling other ordinary sessions; superuser sessions require a superuser. Full activity details can require separate statistics access.

On a managed or company server, ask the administrator to act on a confirmed PID if your role lacks permission.