Find long running queries in postgres — screenshot of til.codes

Find long running queries in postgres

This article details a straightforward SQL query to identify active, long-running queries in PostgreSQL by inspecting `pg_stat_activity`. It's a quick way to pinpoint performance bottlenecks and offers basic steps to further diagnose and terminate rogue processes.

Visit til.codes →

Questions & Answers

What is the primary purpose of this resource on PostgreSQL queries?
This resource provides a practical guide and specific SQL commands to identify and manage long-running SQL queries within a PostgreSQL database. It focuses on using `pg_stat_activity` to monitor query status.
Who would find this guide on long-running PostgreSQL queries most useful?
This guide is most useful for database administrators, developers, or anyone responsible for maintaining the performance and stability of PostgreSQL systems. It helps diagnose and resolve performance issues caused by inefficient queries.
How does this method for finding long-running queries compare to other PostgreSQL monitoring tools?
This method offers a direct, command-line approach using built-in PostgreSQL views (`pg_stat_activity`) rather than relying on external monitoring software. It provides immediate insight without additional setup or tools.
When should I use the techniques described in this article to monitor PostgreSQL queries?
These techniques should be used when experiencing database performance degradation, increased query times, or to proactively identify potential bottlenecks. It's particularly useful for quickly spotting active queries exceeding an acceptable duration.
What specific SQL query is used to find long-running active queries in PostgreSQL according to this resource?
The resource suggests using `SELECT pid, now() - pg_stat_activity.query_start AS duration, state, query FROM pg_stat_activity WHERE state ='active' AND query NOT ILIKE '%pg_stat_activity%' AND (now() - pg_stat_activity.query_start) > interval '5 seconds' ORDER BY duration desc;` to list active queries running longer than 5 seconds.