27.2. The Statistics Collector

PostgreSQL's statistics collector is a subsystem that supports collection and reporting of information about server activity. Presently, the collector can count accesses to tables and indexes in both disk-block and individual-row terms. It also tracks the total number of rows in each table, and information about vacuum and analyze actions for each table. It can also count calls to user-defined functions and the total time spent in each one.

PostgreSQL also supports reporting of the exact command currently being executed by other server processes. This facility is independent of the collector process.

27.2.1. Statistics Collection Configuration

Since collection of statistics adds some overhead to query execution, the system can be configured to collect or not collect information. This is controlled by configuration parameters that are normally set in postgresql.conf. (See Chapter 18 for details about setting configuration parameters.)

The parameter track_activities enables monitoring of the current command being executed by any server process.

The parameter track_counts controls whether statistics are collected about table and index accesses.

The parameter track_functions enables tracking of usage of user-defined functions.

The parameter track_io_timing enables monitoring of block read and write times.

Normally these parameters are set in postgresql.conf so that they apply to all server processes, but it is possible to turn them on or off in individual sessions using the SET command. (To prevent ordinary users from hiding their activity from the administrator, only superusers are allowed to change these parameters with SET.)

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, a permanent copy of the statistics data is stored in the global subdirectory, so that statistics can be retained across server restarts.

27.2.2. Viewing Collected Statistics

Several predefined views, listed in Table 27-1, are available to show the results of statistics collection. Alternatively, one can build custom views using the underlying statistics functions, as discussed in Section 27.2.3.

When using the statistics to monitor current activity, 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.

Table 27-1. Standard Statistics Views

View NameDescription
pg_stat_activity One row per server process, showing information related to the current activity of that process, such as state and current query. See pg_stat_activity for details.
pg_stat_bgwriterOne row only, showing statistics about the background writer process's activity. See pg_stat_bgwriter for details.
pg_stat_databaseOne row per database, showing database-wide statistics. See pg_stat_database for details.
pg_stat_all_tables One row for each table in the current database, showing statistics about accesses to that specific table. See pg_stat_all_tables for details.
pg_stat_sys_tablesSame as pg_stat_all_tables, except that only system tables are shown.
pg_stat_user_tablesSame as pg_stat_all_tables, except that only user tables are shown.
pg_stat_xact_all_tablesSimilar to pg_stat_all_tables, but counts actions taken so far within the current transaction (which are not yet included in pg_stat_all_tables and related views). The columns for numbers of live and dead rows and vacuum and analyze actions are not present in this view.
pg_stat_xact_sys_tablesSame as pg_stat_xact_all_tables, except that only system tables are shown.
pg_stat_xact_user_tablesSame as pg_stat_xact_all_tables, except that only user tables are shown.
pg_stat_all_indexes One row for each index in the current database, showing statistics about accesses to that specific index. See pg_stat_all_indexes for details.
pg_stat_sys_indexesSame as pg_stat_all_indexes, except that only indexes on system tables are shown.
pg_stat_user_indexesSame as pg_stat_all_indexes, except that only indexes on user tables are shown.
pg_statio_all_tables One row for each table in the current database, showing statistics about I/O on that specific table. See pg_statio_all_tables for details.
pg_statio_sys_tablesSame as pg_statio_all_tables, except that only system tables are shown.
pg_statio_user_tablesSame as pg_statio_all_tables, except that only user tables are shown.
pg_statio_all_indexes One row for each index in the current database, showing statistics about I/O on that specific index. See pg_statio_all_indexes for details.
pg_statio_sys_indexesSame as pg_statio_all_indexes, except that only indexes on system tables are shown.
pg_statio_user_indexesSame as pg_statio_all_indexes, except that only indexes on user tables are shown.
pg_statio_all_sequences One row for each sequence in the current database, showing statistics about I/O on that specific sequence. See pg_statio_all_sequences for details.
pg_statio_sys_sequencesSame as pg_statio_all_sequences, except that only system sequences are shown. (Presently, no system sequences are defined, so this view is always empty.)
pg_statio_user_sequencesSame as pg_statio_all_sequences, except that only user sequences are shown.
pg_stat_user_functions One row for each tracked function, showing statistics about executions of that function. See pg_stat_user_functions for details.
pg_stat_xact_user_functionsSimilar to pg_stat_user_functions, but counts only calls during the current transaction (which are not yet included in pg_stat_user_functions).
pg_stat_replicationOne row per WAL sender process, showing statistics about replication to that sender's connected standby server. See pg_stat_replication for details.
pg_stat_database_conflicts One row per database, showing database-wide statistics about query cancels due to conflict with recovery on standby servers. See pg_stat_database_conflicts for details.

The per-index statistics are particularly useful to determine which indexes are being used and how effective they are.

The pg_statio_ views are primarily useful to determine the effectiveness of the buffer cache. When the number of actual disk reads is much smaller than the number of buffer hits, then the cache is satisfying most read requests without invoking a kernel call. However, these statistics do not give the entire story: due to the way in which PostgreSQL handles disk I/O, data that is not in the PostgreSQL buffer cache might still reside in the kernel's I/O cache, and might therefore still be fetched without requiring a physical read. Users interested in obtaining more detailed information on PostgreSQL I/O behavior are advised to use the PostgreSQL statistics collector in combination with operating system utilities that allow insight into the kernel's handling of I/O.

Table 27-2. pg_stat_activity View

ColumnTypeDescription
datidoidOID of the database this backend is connected to
datnamenameName of the database this backend is connected to
pidintegerProcess ID of this backend
usesysidoidOID of the user logged into this backend
usenamenameName of the user logged into this backend
application_nametextName of the application that is connected to this backend
client_addrinetIP address of the client connected to this backend. If this field is null, it indicates either that the client is connected via a Unix socket on the server machine or that this is an internal process such as autovacuum.
client_hostnametextHost name of the connected client, as reported by a reverse DNS lookup of client_addr. This field will only be non-null for IP connections, and only when log_hostname is enabled.
client_portintegerTCP port number that the client is using for communication with this backend, or -1 if a Unix socket is used
backend_starttimestamp with time zoneTime when this process was started, i.e., when the client connected to the server
xact_starttimestamp with time zoneTime when this process' current transaction was started, or null if no transaction is active. If the current query is the first of its transaction, this column is equal to the query_start column.
query_starttimestamp with time zoneTime when the currently active query was started, or if state is not active, when the last query was started
state_changetimestamp with time zoneTime when the state was last changed
waitingbooleanTrue if this backend is currently waiting on a lock
statetextCurrent overall state of this backend. Possible values are:

  • active: The backend is executing a query.

  • idle: The backend is waiting for a new client command.

  • idle in transaction: The backend is in a transaction, but is not currently executing a query.

  • idle in transaction (aborted): This state is similar to idle in transaction, except one of the statements in the transaction caused an error.

  • fastpath function call: The backend is executing a fast-path function.

  • disabled: This state is reported if track_activities is disabled in this backend.

querytextText of this backend's most recent query. If state is active this field shows the currently executing query. In all other states, it shows the last query that was executed.

The pg_stat_activity view will have one row per server process, showing information related to the current activity of that process.

Note: The waiting and state columns are independent. If a backend is in the active state, it may or may not be waiting. If the state is active and waiting is true, it means that a query is being executed, but is being blocked by a lock somewhere in the system.

Table 27-3. pg_stat_bgwriter View

ColumnTypeDescription
checkpoints_timedbigintNumber of scheduled checkpoints that have been performed
checkpoints_reqbigintNumber of requested checkpoints that have been performed
checkpoint_write_timedouble precision Total amount of time that has been spent in the portion of checkpoint processing where files are written to disk, in milliseconds
checkpoint_sync_timedouble precision Total amount of time that has been spent in the portion of checkpoint processing where files are synchronized to disk, in milliseconds
buffers_checkpointbigintNumber of buffers written during checkpoints
buffers_cleanbigintNumber of buffers written by the background writer
maxwritten_cleanbigintNumber of times the background writer stopped a cleaning scan because it had written too many buffers
buffers_backendbigintNumber of buffers written directly by a backend
buffers_backend_fsyncbigintNumber of times a backend had to execute its own fsync call (normally the background writer handles those even when the backend does its own write)
buffers_allocbigintNumber of buffers allocated
stats_resettimestamp with time zoneTime at which these statistics were last reset

The pg_stat_bgwriter view will always have a single row, containing global data for the cluster.

Table 27-4. pg_stat_database View

ColumnTypeDescription
datidoidOID of a database
datnamenameName of this database
numbackendsintegerNumber of backends currently connected to this database. This is the only column in this view that returns a value reflecting current state; all other columns return the accumulated values since the last reset.
xact_commitbigintNumber of transactions in this database that have been committed
xact_rollbackbigintNumber of transactions in this database that have been rolled back
blks_readbigintNumber of disk blocks read in this database
blks_hitbigintNumber of times disk blocks were found already in the buffer cache, so that a read was not necessary (this only includes hits in the PostgreSQL buffer cache, not the operating system's file system cache)
tup_returnedbigintNumber of rows returned by queries in this database
tup_fetchedbigintNumber of rows fetched by queries in this database
tup_insertedbigintNumber of rows inserted by queries in this database
tup_updatedbigintNumber of rows updated by queries in this database
tup_deletedbigintNumber of rows deleted by queries in this database
conflictsbigintNumber of queries canceled due to conflicts with recovery in this database. (Conflicts occur only on standby servers; see pg_stat_database_conflicts for details.)
temp_filesbigintNumber of temporary files created by queries in this database. All temporary files are counted, regardless of why the temporary file was created (e.g., sorting or hashing), and regardless of the log_temp_files setting.
temp_bytesbigintTotal amount of data written to temporary files by queries in this database. All temporary files are counted, regardless of why the temporary file was created, and regardless of the log_temp_files setting.
deadlocksbigintNumber of deadlocks detected in this database
blk_read_timedouble precisionTime spent reading data file blocks by backends in this database, in milliseconds
blk_write_timedouble precisionTime spent writing data file blocks by backends in this database, in milliseconds
stats_resettimestamp with time zoneTime at which these statistics were last reset

The pg_stat_database view will contain one row for each database in the cluster, showing database-wide statistics.

Table 27-5. pg_stat_all_tables View

ColumnTypeDescription
relidoidOID of a table
schemanamenameName of the schema that this table is in
relnamenameName of this table
seq_scanbigintNumber of sequential scans initiated on this table
seq_tup_readbigintNumber of live rows fetched by sequential scans
idx_scanbigintNumber of index scans initiated on this table
idx_tup_fetchbigintNumber of live rows fetched by index scans
n_tup_insbigintNumber of rows inserted
n_tup_updbigintNumber of rows updated
n_tup_delbigintNumber of rows deleted
n_tup_hot_updbigintNumber of rows HOT updated (i.e., with no separate index update required)
n_live_tupbigintEstimated number of live rows
n_dead_tupbigintEstimated number of dead rows
last_vacuumtimestamp with time zoneLast time at which this table was manually vacuumed (not counting VACUUM FULL)
last_autovacuumtimestamp with time zoneLast time at which this table was vacuumed by the autovacuum daemon
last_analyzetimestamp with time zoneLast time at which this table was manually analyzed
last_autoanalyzetimestamp with time zoneLast time at which this table was analyzed by the autovacuum daemon
vacuum_countbigintNumber of times this table has been manually vacuumed (not counting VACUUM FULL)
autovacuum_countbigintNumber of times this table has been vacuumed by the autovacuum daemon
analyze_countbigintNumber of times this table has been manually analyzed
autoanalyze_countbigintNumber of times this table has been analyzed by the autovacuum daemon

The pg_stat_all_tables view will contain one row for each table in the current database (including TOAST tables), showing statistics about accesses to that specific table. The pg_stat_user_tables and pg_stat_sys_tables views contain the same information, but filtered to only show user and system tables respectively.

Table 27-6. pg_stat_all_indexes View

ColumnTypeDescription
relidoidOID of the table for this index
indexrelidoidOID of this index
schemanamenameName of the schema this index is in
relnamenameName of the table for this index
indexrelnamenameName of this index
idx_scanbigintNumber of index scans initiated on this index
idx_tup_readbigintNumber of index entries returned by scans on this index
idx_tup_fetchbigintNumber of live table rows fetched by simple index scans using this index

The pg_stat_all_indexes view will contain one row for each index in the current database, showing statistics about accesses to that specific index. The pg_stat_user_indexes and pg_stat_sys_indexes views contain the same information, but filtered to only show user and system indexes respectively.

Indexes can be used via either simple index scans or "bitmap" index scans. In a bitmap scan the output of several indexes can be combined via AND or OR rules, so it is difficult to associate individual heap row fetches with specific indexes when a bitmap scan is used. Therefore, a bitmap scan increments the pg_stat_all_indexes.idx_tup_read count(s) for the index(es) it uses, and it increments the pg_stat_all_tables.idx_tup_fetch count for the table, but it does not affect pg_stat_all_indexes.idx_tup_fetch.

Note: The idx_tup_read and idx_tup_fetch counts can be different even without any use of bitmap scans, because idx_tup_read counts index entries retrieved from the index while idx_tup_fetch counts live rows fetched from the table. The latter will be less if any dead or not-yet-committed rows are fetched using the index, or if any heap fetches are avoided by means of an index-only scan.

Table 27-7. pg_statio_all_tables View

ColumnTypeDescription
relidoidOID of a table
schemanamenameName of the schema that this table is in
relnamenameName of this table
heap_blks_readbigintNumber of disk blocks read from this table
heap_blks_hitbigintNumber of buffer hits in this table
idx_blks_readbigintNumber of disk blocks read from all indexes on this table
idx_blks_hitbigintNumber of buffer hits in all indexes on this table
toast_blks_readbigintNumber of disk blocks read from this table's TOAST table (if any)
toast_blks_hitbigintNumber of buffer hits in this table's TOAST table (if any)
tidx_blks_readbigintNumber of disk blocks read from this table's TOAST table index (if any)
tidx_blks_hitbigintNumber of buffer hits in this table's TOAST table index (if any)

The pg_statio_all_tables view will contain one row for each table in the current database (including TOAST tables), showing statistics about I/O on that specific table. The pg_statio_user_tables and pg_statio_sys_tables views contain the same information, but filtered to only show user and system tables respectively.

Table 27-8. pg_statio_all_indexes View

ColumnTypeDescription
relidoidOID of the table for this index
indexrelidoidOID of this index
schemanamenameName of the schema this index is in
relnamenameName of the table for this index
indexrelnamenameName of this index
idx_blks_readbigintNumber of disk blocks read from this index
idx_blks_hitbigintNumber of buffer hits in this index

The pg_statio_all_indexes view will contain one row for each index in the current database, showing statistics about I/O on that specific index. The pg_statio_user_indexes and pg_statio_sys_indexes views contain the same information, but filtered to only show user and system indexes respectively.

Table 27-9. pg_statio_all_sequences View

ColumnTypeDescription
relidoidOID of a sequence
schemanamenameName of the schema this sequence is in
relnamenameName of this sequence
blks_readbigintNumber of disk blocks read from this sequence
blks_hitbigintNumber of buffer hits in this sequence

The pg_statio_all_sequences view will contain one row for each sequence in the current database, showing statistics about I/O on that specific sequence.

Table 27-10. pg_stat_user_functions View

ColumnTypeDescription
funcidoidOID of a function
schemanamenameName of the schema this function is in
funcnamenameName of this function
callsbigintNumber of times this function has been called
total_timedouble precisionTotal time spent in this function and all other functions called by it, in milliseconds
self_timedouble precisionTotal time spent in this function itself, not including other functions called by it, in milliseconds

The pg_stat_user_functions view will contain one row for each tracked function, showing statistics about executions of that function. The track_functions parameter controls exactly which functions are tracked.

Table 27-11. pg_stat_replication View

ColumnTypeDescription
pidintegerProcess ID of a WAL sender process
usesysidoidOID of the user logged into this WAL sender process
usenamenameName of the user logged into this WAL sender process
application_nametextName of the application that is connected to this WAL sender
client_addrinetIP address of the client connected to this WAL sender. If this field is null, it indicates that the client is connected via a Unix socket on the server machine.
client_hostnametextHost name of the connected client, as reported by a reverse DNS lookup of client_addr. This field will only be non-null for IP connections, and only when log_hostname is enabled.
client_portintegerTCP port number that the client is using for communication with this WAL sender, or -1 if a Unix socket is used
backend_starttimestamp with time zoneTime when this process was started, i.e., when the client connected to this WAL sender
statetextCurrent WAL sender state
sent_locationtextLast transaction log position sent on this connection
write_locationtextLast transaction log position written to disk by this standby server
flush_locationtextLast transaction log position flushed to disk by this standby server
replay_locationtextLast transaction log position replayed into the database on this standby server
sync_priorityintegerPriority of this standby server for being chosen as the synchronous standby
sync_statetextSynchronous state of this standby server

The pg_stat_replication view will contain one row per WAL sender process, showing statistics about replication to that sender's connected standby server. Only directly connected standbys are listed; no information is available about downstream standby servers.

Table 27-12. pg_stat_database_conflicts View

ColumnTypeDescription
datidoidOID of a database
datnamenameName of this database
confl_tablespacebigintNumber of queries in this database that have been canceled due to dropped tablespaces
confl_lockbigintNumber of queries in this database that have been canceled due to lock timeouts
confl_snapshotbigintNumber of queries in this database that have been canceled due to old snapshots
confl_bufferpinbigintNumber of queries in this database that have been canceled due to pinned buffers
confl_deadlockbigintNumber of queries in this database that have been canceled due to deadlocks

The pg_stat_database_conflicts view will contain one row per database, showing database-wide statistics about query cancels occurring due to conflicts with recovery on standby servers. This view will only contain information on standby servers, since conflicts do not occur on master servers.

27.2.3. Statistics Functions

Other ways of looking at the statistics can be set up by writing queries that use the same underlying statistics access functions used by the standard views shown above. For details such as the functions' names, consult the definitions of the standard views. (For example, in psql you could issue \d+ pg_stat_activity.) The access functions for per-database statistics take a database OID as an argument to identify which database to report on. The per-table and per-index functions take a table or index OID. The functions for per-function statistics take a function OID. Note that only tables, indexes, and functions in the current database can be seen with these functions.

Additional functions related to statistics collection are listed in Table 27-13.

Table 27-13. Additional Statistics Functions

FunctionReturn TypeDescription
pg_backend_pid()integer Process ID of the server process handling the current session
pg_stat_get_activity(integer)setof record Returns a record of information about the backend with the specified PID, or one record for each active backend in the system if NULL is specified. The fields returned are a subset of those in the pg_stat_activity view.
pg_stat_clear_snapshot()void Discard the current statistics snapshot
pg_stat_reset()void Reset all statistics counters for the current database to zero (requires superuser privileges)
pg_stat_reset_shared(text)void Reset some cluster-wide statistics counters to zero, depending on the argument (requires superuser privileges). Calling pg_stat_reset_shared('bgwriter') will zero all the counters shown in the pg_stat_bgwriter view.
pg_stat_reset_single_table_counters(oid)void Reset statistics for a single table or index in the current database to zero (requires superuser privileges)
pg_stat_reset_single_function_counters(oid)void Reset statistics for a single function in the current database to zero (requires superuser privileges)

pg_stat_get_activity, the underlying function of the pg_stat_activity view, returns a set of records containing all the available information about each backend process. Sometimes it may be more convenient to obtain just a subset of this information. In such cases, an older set of per-backend statistics access functions can be used; these are shown in Table 27-14. These access functions use a backend ID number, which ranges from one to the number of currently active backends. The function pg_stat_get_backend_idset provides a convenient way to generate one row for each active backend for invoking these functions. For example, to show the PIDs and current queries of all backends:

SELECT pg_stat_get_backend_pid(s.backendid) AS pid,
       pg_stat_get_backend_activity(s.backendid) AS query
    FROM (SELECT pg_stat_get_backend_idset() AS backendid) AS s;

Table 27-14. Per-Backend Statistics Functions

FunctionReturn TypeDescription
pg_stat_get_backend_idset()setof integerSet of currently active backend ID numbers (from 1 to the number of active backends)
pg_stat_get_backend_activity(integer)textText of this backend's most recent query
pg_stat_get_backend_activity_start(integer)timestamp with time zoneTime when the most recent query was started
pg_stat_get_backend_client_addr(integer)inetIP address of the client connected to this backend
pg_stat_get_backend_client_port(integer)integerTCP port number that the client is using for communication
pg_stat_get_backend_dbid(integer)oidOID of the database this backend is connected to
pg_stat_get_backend_pid(integer)integerProcess ID of this backend
pg_stat_get_backend_start(integer)timestamp with time zoneTime when this process was started
pg_stat_get_backend_userid(integer)oidOID of the user logged into this backend
pg_stat_get_backend_waiting(integer)booleanTrue if this backend is currently waiting on a lock
pg_stat_get_backend_xact_start(integer)timestamp with time zoneTime when the current transaction was started