Document Actions

Viewing current PostgreSQL queries

by Chris Miles last modified 2007-12-11 13:57

An important tool for debugging PostgreSQL performance issues is the ability to view all the currently executing queries. Thankfully this is easy to do. Read on for how.

Configuration

Storing of query strings is usually disabled in PostgreSQL by default.  To enable it, use this line in your postgresql.conf

stats_command_string = true

This setting can be changed on a running database without restarting or effecting open connections by telling the PostgreSQL parent process, postmaster, to reload its config.  Send it a SIGHUP or use the safer pg_ctl command with the reload option.  Example:

pg_ctl reload

Queries

When stats_command_string is enabled the pg_stat_activity table holds all currently active query strings.  The simplest query will show all current query strings along with which database they refer to and the process ID (PID) of the process serving that query.

SELECT datname,procpid,current_query FROM pg_stat_activity

Example:

database1=# SELECT datname,procpid,current_query FROM pg_stat_activity ORDER BY procpid ;
    datname    | procpid | current_query
---------------+---------+---------------
 mydatabaseabc |    2587 | <IDLE>
 anotherdb     |   15726 | SELECT * FROM users WHERE id=123 ; 
 mydatabaseabc |   15851 | <IDLE>
(3 rows)

Each row of pg_stat_activity represents one PostgreSQL process (PostgreSQL uses one server process per connection).

Any processes that are not currently performing any queries will show <IDLE> as the current_query.

Note that queries from all databases within the server will be shown.  If the user querying pg_stat_activity does not have privileges to access a database then it will not show the current_query.

The query_start column can also be used to show when the query started executing.

Another of my favourite queries is to show a top-like view of current queries, grouped by how many of the same query are running at that instant and the usernames belonging to each connection.

SELECT count(*) as cnt, usename, current_query FROM pg_stat_activity GROUP BY usename,current_query ORDER BY cnt DESC;

Example:

database1=# SELECT count(*) as cnt, usename, current_query FROM pg_stat_activity GROUP BY usename,current_query ORDER BY cnt DESC;
cnt |    usename    | current_query
-----+---------------+---------------
   7 | freddykrueger | <IDLE>
   3 | freddykrueger | SELECT name FROM users WHERE id=50;
   1 | postgres      | <IDLE>
(3 rows)

Update

With newer versions of PostgreSQL we get some more details. Here's an example I've used on PostgreSQL 8.2:

SELECT datname,usename,procpid,client_addr,waiting,query_start,current_query FROM pg_stat_activity ;