[postgresql] How to stop/kill a query in postgresql?

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?

This question is related to postgresql

The answer is


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>)