Sobes.tech
Middle

How to find queries in PostgreSQL that run longer than one minute (or 5 seconds)?

sobes.tech AI

Answer from AI

In PostgreSQL, you can find long-running queries using the pg_stat_activity view, which shows current active queries. For example, to find queries running longer than 5 seconds, you can execute:

SELECT pid, now() - query_start AS duration, query
FROM pg_stat_activity
WHERE state = 'active'
  AND now() - query_start > interval '5 seconds'
ORDER BY duration DESC;

If you want to find queries longer than one minute, replace '5 seconds' with '1 minute'.

This query will show the process ID, duration of execution, and the query text itself. For monitoring, you can set up regular runs or use monitoring tools that collect such statistics.