Functions and PL/pgSQL
Encapsulate logic in functions and procedural blocks. Results appear in the same fence: same-line -- comments when short, multiline -- blocks below the sample when not.
Busque em todas as páginas da documentação
Encapsulate logic in functions and procedural blocks. Results appear in the same fence: same-line -- comments when short, multiline -- blocks below the sample when not.
Language SQL - inlinable when simple.
CREATE FUNCTION add_int(a int, b int)
RETURNS int
LANGUAGE sql IMMUTABLE PARALLEL SAFE
AS $$ SELECT a + b $$;
SELECT add_int(2, 3);
-- 5Procedural control flow.
DO $$
DECLARE n int := 1;
BEGIN
n := n + 1;
RAISE NOTICE 'n=%', n;
END $$;
-- NOTICE: n=2Return a set of rows.
CREATE FUNCTION recent_ids(lim int)
RETURNS TABLE (id bigint)
LANGUAGE sql AS $$
SELECT id FROM events ORDER BY ts DESC LIMIT lim
$$;
SELECT * FROM recent_ids(5);
-- up to 5 idsCatch errors inside PL/pgSQL.
DO $$
BEGIN
PERFORM 1 / 0;
EXCEPTION WHEN division_by_zero THEN
RAISE NOTICE 'caught';
END $$;
-- NOTICE: caughtReturns TRIGGER; assigned via CREATE TRIGGER.
CREATE FUNCTION touch_updated()
RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
NEW.updated_at := now();
RETURN NEW;
END $$;
-- CREATE TRIGGER ... BEFORE UPDATE ON t FOR EACH ROW EXECUTE FUNCTION touch_updated();Named outputs without RETURNS TABLE.
CREATE FUNCTION split_name(full text, OUT first text, OUT last text)
LANGUAGE sql AS $$
SELECT split_part(full, ' ', 1), split_part(full, ' ', 2)
$$;IMMUTABLE/STABLE/VOLATILE for planner.
-- IMMUTABLE: pure; STABLE: fixed within scan; VOLATILE: defaultRun with owner rights - use carefully.
CREATE FUNCTION admin_only()
RETURNS void
LANGUAGE sql
SECURITY DEFINER
SET search_path = public
AS $$ SELECT 1 $$;Variable argument lists.
CREATE FUNCTION sum_n(VARIADIC xs int[])
RETURNS int LANGUAGE sql AS $$ SELECT coalesce(sum(x),0) FROM unnest(xs) x $$;
SELECT sum_n(1,2,3);
-- 6PL/pgSQL returning a query result.
CREATE FUNCTION uids()
RETURNS SETOF bigint LANGUAGE plpgsql AS $$
BEGIN
RETURN QUERY SELECT id FROM users;
END $$;Abort with custom message/SQLSTATE.
DO $$ BEGIN
RAISE EXCEPTION 'bad input' USING ERRCODE = '22023';
END $$;
-- ERROR: bad inputON COMMIT DROP temps inside functions carefully.
-- CREATE TEMP TABLE t ON COMMIT DROP AS SELECT ...Include signature when overloaded.
DROP FUNCTION IF EXISTS add_int(int, int);Mark pure SQL functions parallel safe when true.
-- PARALLEL SAFE on add_int enables parallel plansCALL procedures for tx-controlling routines (PG 11+).
CALL reindex_helper();
-- procedures may COMMIT inside (unlike functions)Stack versions: PostgreSQL 18.4 (stable 18, maintenance 17) · pgvector 0.8+
Revisado por Chris St. John·Última atualização: 18 de jul. de 2026