|
| 1 | +-- Workload profile by query type (requires pg_stat_statements) |
| 2 | + |
| 3 | +-- Groups pg_stat_statements entries by first SQL keyword. |
| 4 | +-- Strips block comments (/* ... */) and line comments (-- ...) |
| 5 | +-- before extracting the keyword. |
| 6 | + |
| 7 | +\if :postgres_dba_pgvers_13plus |
| 8 | +with data as ( |
| 9 | + select |
| 10 | + lower((regexp_match( |
| 11 | + regexp_replace( |
| 12 | + regexp_replace(query, '/\*.*?\*/', '', 'gs'), |
| 13 | + '^\s*(--[^\n]*\n\s*)*', '', 'g' |
| 14 | + ), |
| 15 | + '^\s*(\w+)' |
| 16 | + ))[1]) as word, |
| 17 | + calls, |
| 18 | + total_exec_time, |
| 19 | + total_plan_time, |
| 20 | + rows |
| 21 | + from pg_stat_statements |
| 22 | +) |
| 23 | +select |
| 24 | + coalesce(word, '???') as "Query Type", |
| 25 | + sum(calls) as "Calls", |
| 26 | + round( |
| 27 | + 100.0 * sum(calls) / nullif(sum(sum(calls)) over (), 0), 1 |
| 28 | + ) as "Calls %", |
| 29 | + round(sum(total_exec_time)::numeric, 1) as "Exec (ms)", |
| 30 | + round( |
| 31 | + 100.0 * sum(total_exec_time) / nullif(sum(sum(total_exec_time)) over (), 0), 1 |
| 32 | + ) as "Exec %", |
| 33 | + round(sum(total_plan_time)::numeric, 1) as "Plan (ms)", |
| 34 | + round( |
| 35 | + (sum(total_exec_time) / nullif(sum(calls), 0))::numeric, 3 |
| 36 | + ) as "Avg (ms/call)", |
| 37 | + sum(rows) as "Rows" |
| 38 | +from data |
| 39 | +group by word |
| 40 | +order by sum(total_exec_time) desc; |
| 41 | +\else |
| 42 | +with data as ( |
| 43 | + select |
| 44 | + lower((regexp_match( |
| 45 | + regexp_replace( |
| 46 | + regexp_replace(query, '/\*.*?\*/', '', 'gs'), |
| 47 | + '^\s*(--[^\n]*\n\s*)*', '', 'g' |
| 48 | + ), |
| 49 | + '^\s*(\w+)' |
| 50 | + ))[1]) as word, |
| 51 | + calls, |
| 52 | + total_time, |
| 53 | + rows |
| 54 | + from pg_stat_statements |
| 55 | +) |
| 56 | +select |
| 57 | + coalesce(word, '???') as "Query Type", |
| 58 | + sum(calls) as "Calls", |
| 59 | + round( |
| 60 | + 100.0 * sum(calls) / nullif(sum(sum(calls)) over (), 0), 1 |
| 61 | + ) as "Calls %", |
| 62 | + round(sum(total_time)::numeric, 1) as "Time (ms)", |
| 63 | + round( |
| 64 | + 100.0 * sum(total_time) / nullif(sum(sum(total_time)) over (), 0), 1 |
| 65 | + ) as "Time %", |
| 66 | + round( |
| 67 | + (sum(total_time) / nullif(sum(calls), 0))::numeric, 3 |
| 68 | + ) as "Avg (ms/call)", |
| 69 | + sum(rows) as "Rows" |
| 70 | +from data |
| 71 | +group by word |
| 72 | +order by sum(total_time) desc; |
| 73 | +\endif |
0 commit comments