Postgresql

Postgres - 獲取分配給變數的查詢成本

  • September 30, 2016

要獲取estimated cost查詢的 ,我使用EXPLAIN SELECT column FROM table;,來獲取current cost查詢的 ,我正在使用EXPLAIN ANALYSE SELECT column FROM table;,我的問題是如何cost自動獲取查詢的 ,而無需explain手動執行每個查詢。

我需要類似的東西:

DECLARE cost integer;
DECLARE highercost integer;
DECLARE query text;

highercost := 0;
i := 0;
query = '';

WHILE i < array_length( queryarray ,1) LOOP

   cost := explain analyse queryarray[i];

   IF cost > highercost THEN

       highercost := cost;
       query := queryarray[i];

   END IF;

   i := i+1;

END LOOP;

這個想法是創建一個腳本來檢查 a 中的查詢log並執行psql,或者將查詢複製log到數據庫中的表並執行plain SQL以驗證最昂貴的查詢,目前正是我所尋求的,無需擔心關於cost查詢的真實性**(“成本”X“每分鐘執行的次數”)**,成本INSERTUPDATE等等DELETE

我希望這是可能的,如果沒有,還有另一種方法可以搜尋昂貴的查詢而無需一一檢查?

基於這個答案 [https://pt.stackoverflow.com/questions/155113]$$ 1 $$:

CREATE or REPLACE function custo_consulta(_consulta text[])
returns table (consulta text, custo_execucao numeric, tempo_execucao numeric ) as '
declare custo text;
begin
   foreach consulta in array _consulta loop
       execute ''EXPLAIN ( FORMAT JSON, ANALYZE ) '' || consulta INTO custo;
       custo_execucao := split_part(split_part(custo, ''"Total Cost": '', 2), '','', 1);
       tempo_execucao := split_part(split_part(custo, ''"Actual Total Time": '', 2), '','', 1);
       return next;
   end loop;
end;
' language plpgsql;

SELECT *
FROM custo_consulta(array['SELECT COUNT(*) FROM syo_evento WHERE id_grupoevento = ''OPORTUNIDADE''', 'SELECT COUNT(*) FROM syo_evento WHERE id_grupoevento = ''REVISAO'''])
ORDER BY custo_execucao desc;

結果


consulta                                                               custo_execucao     tempo_execucao    
SELECT COUNT(*) FROM syo_evento WHERE id_grupoevento = 'REVISAO'       38426,44           128,267           
SELECT COUNT(*) FROM syo_evento WHERE id_grupoevento = 'OPORTUNIDADE'  38252,65           123,996           

**只是另一個問題,我在使用$$**時收到錯誤,但這將得到解決。

引用自:https://dba.stackexchange.com/questions/150796