【问题标题】:postgresql how to run explain analyze on foreach looppostgresql如何在foreach循环上运行解释分析
【发布时间】:2018-11-03 17:09:45
【问题描述】:

我正在尝试在 postgresql 中运行 'explain analyze' foreach 循环,但在 postgres 文档中没有找到合适的示例。谁能帮帮我。

这是一个例子

CREATE OR REPLACE FUNCTION xyz() RETURNS TRIGGER AS $xyz$
DECLARE
        idList integer[];

        aa integer;
        bb bigint;
        cc integer;
        dd smallint;

BEGIN
        IF NEW.severity = 7
        THEN     
             idList := array(select someid from sometable where someid like NEW.someid);

        END IF;
             FOREACH Id in ARRAY alarmIdList LOOP
                 select a, b, c, d
                        into aa, bb, cc , dd
                 from SomeActivetable where someid = Id;

                 insert into SomeTable2(ba, bb, bc, bd)
                     values(aa, bb, 6, dd);
             END LOOP;

        END IF;
        RETURN NEW;
END;
$xyz$ LANGUAGE plpgsql;

谢谢, 古拉夫

【问题讨论】:

  • 请分享一个你有的plpgsql
  • 您不能在 PL/pgSQL 语句上运行 explain。这只适用于SQL statements
  • 举个例子,如果我想分析整个函数。有什么办法?
  • 您不需要foreach 循环或中间变量来保存idlist,您可以使用单个insert ... select ... 语句来做到这一点:dpaste.com/0H9F015where someid like new.someid 不会有什么感觉。 LIKE 用于字符串值,而不是整数值。
  • 当然可以,但现在我有兴趣分析每个循环或函数。

标签: postgresql query-performance sql-execution-plan explain


【解决方案1】:

嗯,有一个有点奇怪的方法。请参阅下面的“概念证明” - 根据您的需要进行调整...

do $$
declare
    _idlist int[] := '{10,20,30}';
    i int;
    _q text;
    _t text;
begin
    foreach i in array _idlist loop
        _q := 'explain analyze select '||i;
        raise notice 'query: %', _q;
        for _t in execute _q loop
            raise notice '%', _t;
        end loop;
    end loop;
end; $$ language plpgsql;   

将在 pgAdmin(或命令行上的 STDERR)的“消息”窗口中为您提供如下输出:

NOTICE:  query: explain analyze select 10
NOTICE:  Result  (cost=0.00..0.01 rows=1 width=4) (actual time=0.001..0.001 rows=1 loops=1)
NOTICE:  Planning time: 0.003 ms
NOTICE:  Execution time: 0.012 ms
NOTICE:  query: explain analyze select 20
NOTICE:  Result  (cost=0.00..0.01 rows=1 width=4) (actual time=0.001..0.001 rows=1 loops=1)
NOTICE:  Planning time: 0.004 ms
NOTICE:  Execution time: 0.004 ms
NOTICE:  query: explain analyze select 30
NOTICE:  Result  (cost=0.00..0.01 rows=1 width=4) (actual time=0.000..0.000 rows=1 loops=1)
NOTICE:  Planning time: 0.004 ms
NOTICE:  Execution time: 0.003 ms
DO

Query returned successfully in 127 msec.

【讨论】:

    猜你喜欢
    • 2022-01-22
    • 2014-06-18
    • 2019-07-15
    • 2020-05-29
    • 2023-03-27
    • 2020-11-18
    • 2019-05-26
    • 1970-01-01
    • 2016-03-11
    相关资源
    最近更新 更多