Stop (long) running SQL query in PostgreSQL when session or requests no longer exist?

SqlPostgresql

Sql Problem Overview


I'm not sure where to start on addressing this issue but if I have a AJAX web application that sends requests to the server and runs long queries on the database (postgresql in my case), is there a way to stop or kill the queries if while still running, the user refreshes the page or closes the session...etc?

Sql Solutions


Solution 1 - Sql

To stop the query:

SELECT pg_cancel_backend(procpid);

To kill the database connection:

SELECT pg_terminate_backend(procpid);

To get an overview of the current transactions, to get the proced id's:

SELECT * FROM pg_stat_activity;

http://www.postgresql.org/docs/current/interactive/functions-admin.html

Solution 2 - Sql

Considering your psql configured to run and connect to current dev database this one liner comes handy in development when testing complicated queries which can hung, just kills whatever runs:

If not configured properly - add flags for user/password/database

psql -c "SELECT procpid FROM pg_stat_activity;" -t | xargs -n1 -I {} psql -c "SELECT pg_cancel_backend({})"

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
QuestionKenny ShenView Question on Stackoverflow
Solution 1 - SqlFrank HeikensView Answer on Stackoverflow
Solution 2 - SqlTigraView Answer on Stackoverflow