Stopping a blocking query in postgresql

Problem

You run a query in PostgreSQL that takes a lot of time to finish (maybe because of an error) and you want to stop/kill it as it is blocking other queries in db.

Solution

You will need to find the pid for the query, either by using a GUI program like Pgadmin or by issuing the following to an SQL prompt:

select * from pg_stat_activity

make a note of the pid of the query that you want to stop/kill and issue the following:

select pg_cancel_backend(pid)