# Killing long-running PostgreSQL processes

Commonly used commands for inspecting processes in PostgreSQL by querying the `pg_stat_activity` view in the `pg_catalog` schema.

## Find all active processes.

```sql
SELECT * FROM pg_stat_activity WHERE state = 'active';
```

## Cancel process by PID

`pg_cancel_backend()` cancels the running query and keeps the process running.

```sql
SELECT pg_cancel_backend(<insert-pid>);
```

## Kill process by PID

`pg_terminate_backend()` kills the process and, thus, the database connection.

```sql
SELECT pg_terminate_backend(<insert-pid>);
```

## Find all active processes running for more than 5 minutes

```sql
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 minute'
  AND pid <> pg_backend_pid()
  AND state = 'active'
ORDER BY
  duration DESC;
```

## Find and kill all active queries running for more than 5 minutes by ‘name’

Remember the `pg_stat_activity`\-view includes processes that are not connections, such as WAL senders and receivers for replication.

```sql
SELECT
  pg_terminate_backend(pid)
FROM
  pg_stat_activity
WHERE
  (now() - pg_stat_activity.query_start) > interval '5 minute'
  AND pid <> pg_backend_pid()
  AND state = 'active'
  AND query like '%name%';
```
