Skip to content
Database

pg_stat_statements:查询性能监控

pg_stat_statements 是一个数据库扩展,它提供了一个同名视图,用于跟踪在数据库上执行的 SQL 语句的统计信息。下面的表格展示了一些可用的统计数据和元数据:

列名列类型描述
useridoid(参考 pg_authid.oid)执行该语句的用户的OID
dbidoid(参考 pg_database.oid)执行该语句的数据库的 OID
toplevelbool如果查询作为顶层语句执行则为真(如果 pg_stat_statements.track 设置为 top,则始终为真)
queryidbigint用于识别相同标准化查询的哈希码。
querytext代表性声明的文字
plansbigint语句被规划的次数(如果启用了 pg_stat_statements.track_planning,否则为零)
total_plan_timedouble precision计划语句所花费的总时间,单位毫秒(如果启用了 pg_stat_statements.track_planning,否则为零)
min_plan_timedouble precision计划语句所花费的最少时间,单位为毫秒(如果启用了 pg_stat_statements.track_planning,否则为零)

完整的统计列表可以在 pg_stat_statements 文档 中找到。

🌐 A full list of statistics is available in the pg_stat_statements docs.

想了解更多关于查询优化的信息,可以看看查询性能指南。

🌐 For more information on query optimization, check out the query performance guide.

启用扩展 #

🌐 Enable the extension

  1. 在仪表板中转到数据库页面。
  2. 点击侧边栏的 扩展。
  3. 搜索“pg_stat_statements”并启用该扩展。

检查活动 #

🌐 Inspecting activity

pg_stat_statements 的一个常见用途是跟踪昂贵或缓慢的查询。pg_stat_statements 视图包含每个执行过的查询的行,并内嵌了统计信息。例如,你可以利用这些统计数据来识别针对某个表的经常执行且缓慢的查询。

🌐 A common use for pg_stat_statements is to track down expensive or slow queries. The pg_stat_statements view contains a row for each executed query with statistics inlined. For example, you can leverage the statistics to identify frequently executed and slow queries against a given table.

select
calls,
mean_exec_time,
max_exec_time,
total_exec_time,
stddev_exec_time,
query
from
pg_stat_statements
where
calls > 50 -- at least 50 calls
and mean_exec_time > 2.0 -- averaging at least 2ms/call
and total_exec_time > 60000 -- at least one minute total server time spent
and query ilike '%user_in_organization%' -- filter to queries that touch the user_in_organization table
order by
calls desc

根据结果,我们可以明智地决定优化或索引哪些查询。

🌐 From the results, we can make an informed decision about which queries to optimize or index.

资源 #

🌐 Resources