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

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

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

© 2026 Panda Capital Oy Ab. All rights reserved.