# PostgreSQL
How to find and kill a hanging query
First, check all the processes that are running:
```
SELECT * FROM pg_stat_activity WHERE state = 'active';
```
Find processes which are running longer than 5 min:
```
SELECT
pid,
now() - pg_stat_activity.query_start AS duration,
query,
state
FROM pg_stat_activity
WHERE (now() - pg_stat_activity.query_start) > interval '5 minutes';
```
So you can identify the PID of the hanging query you want to terminate, run this:
```
SELECT pg_cancel_backend(PID);
```
This query might take a while to kill the query, so if you want to kill it the hard way, run this instead:
```
SELECT pg_terminate_backend(PID);
```