How do I terminate the abnormal execution of an SQL statement?

更新时间:
复制 MD 格式

When a query is running abnormally or blocking other sessions, use pg_cancel_backend() or pg_terminate_backend() to stop it and restore normal operation.

Step 1: Identify the problem query

Query pg_stat_activity to find active sessions and their PIDs:

SELECT current_query, procpid
FROM pg_stat_activity;
ColumnDescription
procpidBackground process ID
current_querySQL statement currently running

Step 2: Stop the query

Once you have the PID, choose the method that matches your intent:

Cancel the query (soft interrupt)

SELECT pg_cancel_backend(pg_stat_activity.procpid)
FROM pg_stat_activity
WHERE procpid <> pg_backend_pid()
  AND current_query LIKE 'SELECT%'; -- SELECT must be uppercase

Terminate the session (hard kill)

SELECT pg_terminate_backend(pg_stat_activity.procpid)
FROM pg_stat_activity
WHERE procpid <> pg_backend_pid()
  AND current_query LIKE 'SELECT%'; -- SELECT must be uppercase

Both functions return t when successful.

Note The LIKE 'SELECT%' filter only matches queries that start with SELECT (uppercase). To stop all active queries regardless of type, remove the current_query filter.

Permissions

pg_cancel_backend() and pg_terminate_backend() can only signal queries that belong to the current user or to users with fewer privileges. If queries from other users are running in the background, the following error appears:

ERROR: must be superuser or rds_superuser to signal other server processes

This error does not interrupt the execution of the cancel or terminate operations.