How to stop/kill a query in postgresql?

Postgresql

Postgresql Problem Overview


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?

Postgresql Solutions


Solution 1 - Postgresql

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndong ZhanView Question on Stackoverflow
Solution 1 - PostgresqlAndong ZhanView Answer on Stackoverflow