current PostgreSQL queries View

An important tool for debugging PostgreSQL performance issues is the ability to view all the currently executing queries. 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 ;
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 |
 anotherdb     |   15726 | SELECT * FROM users WHERE id=123 ;  
 mydatabaseabc |   15851 |
(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 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 |
   3 | freddykrueger | SELECT name FROM users WHERE id=50;
   1 | postgres      |
(3 rows)

without restarting the server-drop all connections in postgreSql

I want to drop all connections (sessions) that are currently opened to a specific PostgreSQL database but without restarting the server or disconnecting connections to other databases.


Method 1.
Depending on your version of postgresql you might run into a bug, that makes pg_stat_activity to omit active connections from dropped users. These connections are also not shown inside pgAdminIII.
If you are doing automatic testing (in which you also create users) this might be a probable scenario.

In this case you need to revert to queries like:
 SELECT pg_terminate_backend(pg_stat_activity.procpid)
 FROM pg_stat_get_activity(NULL::integer)
 WHERE datid=(SELECT oid from pg_database where datname = ‘your_database’);


Method 2.
The query like this should help (assuming the database is named ‘db’):
select pg_terminate_backend(pid) from pg_stat_activity where datname=’db’;

pid used to be called procpid, so if you’re using a version of postgres older than 9.2 you could try the following:
select pg_terminate_backend(procpid) from pg_stat_activity where datname=’db’;

However you have to be a superuser to disconnect other users.
It might also be useful to REVOKE CONNECT ON DATABASE FROM PUBLIC or something similar, and then GRANT it afterward.

Method 3.
This can be used to “free” a database from client connections, so that you for example can rename it:
SELECT pg_terminate_backend(procpid) FROM pg_stat_activity WHERE datname=’current_db’;
ALTER DATABASE current_db RENAME TO old_db;
ALTER DATABASE new_db RENAME TO current_db;

Be aware that this might cause problematic behaviour to your client apps. Data actualy should not be currupted due to using transactions.



Method 4.
$ ps aux | grep DATABASE_NAME
          51191
 postgres: user DATABASE_NAME [local] idle
then kill the process

$ kill -9 51191

Statistics Collector in postgresql

Statistics Collection Configuration in postgresql.conf the system can be configured to collect or not collect information

The parameter track_counts controls whether statistics are collected about table and index accesses.T
he parameter track_functions enables tracking of usage of user-defined functions.
The parameter track_io_timing enables monitoring of block read and write times


view statistics:-
The statistics collector transmits the collected information to other PostgreSQL processes through temporary files. These files are stored in the directory named by the stats_temp_directory parameter, pg_stat_tmp by default. For better performance, stats_temp_directory can be pointed at a RAM-based file system, decreasing physical I/O requirements. When the server shuts down cleanly, a permanent copy of the statistics data is stored in the pg_stat subdirectory, so that statistics can be retained across server restarts. When recovery is performed at server start (e.g. after immediate shutdown, server crash, and point-in-time recovery), all statistics counters are reset.

When using the statistics to monitor collected data, it is important to realize that the information does not update instantaneously. Each individual server process transmits new statistical counts to the collector just before going idle; so a query or transaction still in progress does not affect the displayed totals. Also, the collector itself emits a new report at most once per PGSTAT_STAT_INTERVAL milliseconds (500 ms unless altered while building the server). So the displayed information lags behind actual activity. However, current-query information collected by track_activities is always up-to-date.

Another important point is that when a server process is asked to display any of these statistics, it first fetches the most recent report emitted by the collector process and then continues to use this snapshot for all statistical views and functions until the end of its current transaction. So the statistics will show static information as long as you continue the current transaction. Similarly, information about the current queries of all sessions is collected when any such information is first requested within a transaction, and the same information will be displayed throughout the transaction. This is a feature, not a bug, because it allows you to perform several queries on the statistics and correlate the results without worrying that the numbers are changing underneath you. But if you want to see new results with each query, be sure to do the queries outside any transaction block. Alternatively, you can invoke pg_stat_clear_snapshot(), which will discard the current transaction’s statistics snapshot (if any). The next use of statistical information will cause a new snapshot to be fetched.

A transaction can also see its own statistics (as yet untransmitted to the collector) in the views pg_stat_xact_all_tables, pg_stat_xact_sys_tables, pg_stat_xact_user_tables, and pg_stat_xact_user_functions. These numbers do not act as stated above; instead they update continuously throughout the transaction.