数据库是较大型的应用,对于繁忙的数据库,需要消耗大量的内存、CPU、IO、网络资源。SQL 优化是数据库优化的手段之一,而为了达到 SQL 优化的最佳效果,您首先需要了解最消耗资源的 SQL(Top SQL),例如 IO 消耗最高的 SQL。
数据库资源分为多个维度、CPU、内存、IO 等,为能够从各个维度层面查找最消耗数据库资源的 SQL,您可以使用 pg_stat_statements 插件统计数据库的资源开销和分析 Top SQL。
本文将通过示例介绍如何创建 pg_stat_statements 插件、如何分析 Top SQL 以及如何重置统计信息。
创建 pg_stat_statements 插件
执行如下命令,在需要查询 TOP SQL 的数据库中,创建 pg_stat_statements 插件。
Name | Type | References | Description |
userid | oid | pg_authid.oid | OID of user who executed the statement. |
dbid | oid | pg_database.oid | OID of database in which the statement was executed. |
queryid | bigint | - | Internal hash code, computed from the statement’s parse tree. |
query | text | - | Text of a representative statement. |
calls | bigint | - | Number of times executed. |
total_time | double precision | - | Total time spent in the statement, in milliseconds. |
min_time | double precision | - | Minimum time spent in the statement, in milliseconds. |
max_time | double precision | - | Maximum time spent in the statement, in milliseconds. |
mean_time | double precision | - | Mean time spent in the statement, in milliseconds. |
stddev_time | double precision | - | Population standard deviation of time spent in the statement, in milliseconds. |
rows | bigint | - | Total number of rows retrieved or affected by the statement. |
shared_blks_hit | bigint | - | Total number of shared block cache hits by the statement. |
shared_blks_read | bigint | - | Total number of shared blocks read by the statement. |
shared_blks_dirtied | bigint | - | Total number of shared blocks dirtied by the statement. |
shared_blks_written | bigint | - | Total number of shared blocks written by the statement. |
local_blks_hit | bigint | - | Total number of local block cache hits by the statement. |
local_blks_read | bigint | - | Total number of local blocks read by the statement. |
local_blks_dirtied | bigint | - | Total number of local blocks dirtied by the statement. |
local_blks_written | bigint | - | Total number of local blocks written by the statement. |
temp_blks_read | bigint | - | Total number of temp blocks read by the statement. |
temp_blks_written | bigint | - | Total number of temp blocks written by the statement. |
blk_read_time | double precision | - | Total time the statement spent reading blocks, in milliseconds (if track_io_timing is enabled, otherwise zero). |
blk_write_time | double precision | - | Total time the statement spent writing blocks, in milliseconds (if track_io_timing is enabled, otherwise zero). |
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。