How to Stop/Kill a Query in Postgresql? [Duplicate]

This question is while postmaster is running your query in the background, how to kill or stop it?

For example, your shell or any frontend may be disconnected due to network issue, you cannot use ctrl-D to kill it but the background postmaster is still running your query. How to kill it?

2

What I did is first check what are the running processes by

SELECT * FROM pg_stat_activity WHERE state = 'active';

Find the process you want to kill, then type:

SELECT pg_cancel_backend(<pid of the process>)

This basically "starts" a request to terminate gracefully, which may be satisfied after some time, though the query comes back immediately.

If the process cannot be killed, try:

SELECT pg_terminate_backend(<pid of the process>)
6
Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.

Share this article
Twitter Facebook Pinterest