PostgreSQL stores the information about, among others, the running tasks in the pg_stat_activity table:
postgres=# \x on Expanded display is on. postgres=# select datid, datname, pid, usename, application_name, query, query_start from pg_stat_activity; -[ RECORD 3 ]----+------------------------------------------------------------------------------------------------- datid | 13067 datname | postgres pid | 66 usename | postgres application_name | psql query | select datid, datname, pid, usename, application_name, query, query_start from pg_stat_activity; query_start | 2018-12-24 07:15:24.419923+00
Now we can look for the process we want to kill. The attribute used to kill a task is the process id value (pid). The first method we can use is SELECT pg_cancel_backend(pid).It simply cancels the query and keeps the connection untouched. But sometimes it may not work and you may be forced to use more violent query: SELECT pg_terminate_backend(pid). Unlike the previous one, it not only terminates the query but also shuts down the whole database connection. Therefore, when a client connected to the database and issued different queries, the pg_terminate_backend command will stop them all.
Hence, it's safer to use pg_cancel_backend which is the equivalent of SIGTERM. Before terminating the task, the server has a chance to clean up all inconsistencies. pg_terminate_backend behaves as SIGKILL (kill -9) and the server may decide to restart in order to recover the cleaned state.