Friday, February 1, 2008

Watching PostgreSQL queries

I came across a handy way to monitor the queries that are currently running in a PostgreSQL database. First, edit postgresql.conf and set stats_command_string to on. Then tell postmaster to reload the configuration file with something like /etc/init.d/postgresql reload. Once that's done, you can find out which queries have been running the longest with something like:
SELECT      CURRENT_TIMESTAMP - query_start,
            current_query
FROM        pg_catalog.pg_stat_activity
ORDER BY    1 desc
yielding something like this:
    ?column?     | current_query 
-----------------+---------------
 00:04:55.796107 | SELECT COUNT(*) FROM price
                 | WHERE id = $1
 00:04:41.025283 | 
 00:02:04.016315 | 
(3 rows)
Remember to disable stats_command_string when you're finished. It's rumored to have a minor impact on performance.

0 comments: