Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sql

postgresql

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?

like image 344
Kenny Shen Avatar asked Aug 18 '10 02:08

Kenny Shen


People also ask

How do I stop a running query in PostgreSQL?

The pg_cancel_backend() function is used to simply cancel out the query of a database using the process ID for a particular query. It doesn't terminate the database connection. While the pg_terminate_backend() function cancels the query using the process ID for the query and shuts the connected database.

How do you stop a query execution in pgAdmin?

Go to Dashboard in your pgAdmin. At the bottom, in the Server Activity section, under the Sessions Tab, you can see all the Active queries. Now, notice the cross button and the Stop button to the left of each query.

How do you check which query is running in Postgres?

A simple select * from pg_stat_activity will provide a snapshot of what is happening on your PostgreSQL database, with one line per current transaction, and the key columns: datname: The database name that the query is running on.


1 Answers

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

like image 175
Frank Heikens Avatar answered Sep 17 '22 18:09

Frank Heikens