Postgres

Active queries

SELECT pid,
       usename,
       client_addr,
       now()-query_start AS elapsed,
       wait_event_type,
       wait_event,
       state
FROM pg_stat_activity
ORDER BY elapsed DESC;

Active queries with truncated query

SELECT pid,
       application_name,
       usename,
       client_addr,
       now()-query_start AS elapsed,
       wait_event_type,
       wait_event,
       state,
       substring(regexp_replace(replace(query, E'\n', ' '), '\s+', ' ', 'g'), 1, 50)
FROM pg_stat_activity
ORDER BY elapsed DESC;

Active queries without client read

SELECT pid,
       application_name,
       usename,
       client_addr,
       now()-query_start AS elapsed,
       wait_event_type,
       wait_event,
       state,
       substring(regexp_replace(replace(query, E'\n', ' '), '\s+', ' ', 'g'), 1, 50)
FROM pg_stat_activity
WHERE wait_event_type != 'Client'
ORDER BY elapsed DESC;

Locked queries

SELECT application_name,
       usename,
       client_addr,
       now()-query_start AS elapsed,
       wait_event_type,
       wait_event,
       state,
       substring(regexp_replace(replace(query, E'\n', ' '), '\s+', ' ', 'g'), 1, 50)
FROM pg_stat_activity
WHERE pid IN
    (SELECT pid
     FROM pg_locks
     WHERE locktype = 'advisory')
ORDER BY elapsed DESC;

Kill query

GRANT pg_signal_backend TO USERNAME;
select pg_cancel_backend(pid);

Output to file

\copy (select a, b, c from table order by c) 
to 'filename.csv' 
with (delimiter ',', format CSV, header, force_quote *);