PostgreSQL:是否可以打印 运行 查询的查询计划?

PostgreSQL: Is it possible to print the query plan of a running query?

我 运行 定期查询相同的报告,大多数情况下查询会在几分钟内完成。但是,它有时会以不确定的方式卡住数小时。当它卡住时,我用 EXPLAIN ANALYZE 重复了同样的查询,但后者很快就完成了。

为什么会这样?如何获取 运行 查询的执行计划?

生成执行计划时,PostgreSQL 查询计划器relies heavily on table statistics. The statistics are updated by ANALYZE command, and the autovacuum process。 在您的情况下,似乎大多数时候统计信息都是正确的,但有时它们会过时,从而导致查询计划效率低下。它可能发生在批量行插入或更新之后。

为了在查询完成后查看查询计划,请使用 auto_explain 模块。例如,以下命令将会话配置为记录所有持续超过一个小时的查询的计划:

LOAD 'auto_explain';
SET auto_explain.log_min_duration = '1h';
SET auto_explain.log_analyze = true;

也可以在postgresql.conf中设置参数。必须在查询开始之前加载模块。

如果您想获取已经 运行 查询的计划,并且不想等待其完成,您可以使用 https://[ 提供的外部脚本=26=].com/StarfishStorage/explain-running-query.该脚本基于 auto_explain 模块。它将 gdb 附加到 PostgreSQL 后端进程,并打印查询计划。