How to Kill a Running Query in PostgreSQL

Last updated July 24, 2026 · By the SaturnSQL team

Find the backend pid in pg_stat_activity, then pg_cancel_backend(pid) to cancel the query gracefully or pg_terminate_backend(pid) to kill the whole connection.

Find long-running queries

pg_stat_activity has one row per connection. Filtering out idle leaves the sessions actually doing something, and ordering by runtime puts the worst offender first. Read state before acting: idle in transaction means a client is holding a transaction open without running anything, which blocks vacuum and is often the real problem.

SELECT pid, now() - query_start AS runtime, state, left(query, 80) AS query
FROM pg_stat_activity
WHERE state <> 'idle'
ORDER BY runtime DESC;

Cancel or terminate

pg_cancel_backend stops the running statement and leaves the connection alive, so the client sees a query error and can carry on. pg_terminate_backend closes the whole connection and rolls back its transaction. Try cancel first. Both require superuser or membership of pg_signal_backend, and neither is instant, since the backend only reacts at its next check point.

SELECT pg_cancel_backend(12345);    -- cancel the query
SELECT pg_terminate_backend(12345); -- drop the connection

Run this in SaturnSQL

SaturnSQL is a browser-based SQL editor for teams: shared query library, schema-aware autocomplete, and scheduled exports to Google Sheets and Slack.

Try it free

Related PostgreSQL guides