pg_stat_user_functions Call Timing
Read pg_stat_user_functions to see how often each PL/pgSQL function runs and how much time it consumes, gated by track_functions.
Code
-- 函数级统计默认关闭:track_functions 控制开关(pl 只统计 PL/pgSQL)
SHOW track_functions; -- 默认 none;改 pl/all 后需要新会话才生效
CREATE FUNCTION add_tax(cents int) RETURNS int LANGUAGE plpgsql AS $$
BEGIN
RETURN cents + cents * 20 / 100;
END $$;
CREATE FUNCTION trim_note(t text) RETURNS text LANGUAGE sql
RETURNS NULL ON NULL INPUT AS $$ SELECT btrim(t) $$;
-- 调用后统计会累积:calls 次数、total_time/self_time 微秒
SELECT add_tax(100), trim_note(' hi ');
-- self_time 排除被调用子函数的耗时;行级触发器不计入函数统计
SELECT schemaname, funcname, calls, total_time, self_time
FROM pg_stat_user_functions
WHERE schemaname = 'public'
ORDER BY total_time DESC;How it works
What runs here is SELECT / CREATE — pg_stat_user_functions are the objects involved.
Mechanically, the statements are built from: a WHERE clause constraining which rows the statement operates on; an ORDER BY that fixes the output order.
Applying it
Point it at the pg_stat_user_functions table.
Statements that matter
SELECT schemaname, funcname, calls, total_time, self_time
FROM pg_stat_user_functions
WHERE schemaname = 'public'
ORDER BY total_time DESC;
CREATE FUNCTION trim_note(t text) RETURNS text LANGUAGE sql
RETURNS NULL ON NULL INPUT AS $$ SELECT btrim(t) $$;
CREATE FUNCTION add_tax(cents int) RETURNS int LANGUAGE plpgsql AS $$
BEGIN
RETURN cents + cents * 20 / 100;
END $$;
Interactive Tools for This Topic
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which tables does the SQL touch?
- `pg_stat_user_functions`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.