RefLib

Reference library for AI

Back

postgresql_16:7.1.65.5 Examples

PostgreSQL 16 > Reference > SQL Commands > CREATE FUNCTION > Examples

Add two integers using an SQL function: CREATE FUNCTION add(integer, integer) RETURNS integer AS 'select $1 + $2;' LANGUAGE SQL IMMUTABLE RETURNS NULL ON NULL INPUT; The same function written in a more SQL-conforming style, using argument names and an unquoted body: CREATE FUNCTION add(a integer, b integer) RETURNS integer LANGUAGE SQL IMMUTABLE RETURNS NULL ON NULL INPUT RETURN a + b;

Increment an integer, making use of an argument name, in PL/pgSQL: CREATE OR REPLACE FUNCTION increment(i integer) RETURNS integer AS $$ BEGIN RETURN i + 1; END; $$ LANGUAGE plpgsql;

Return a record containing multiple output parameters: CREATE FUNCTION dup(in int, out f1 int, out f2 text) AS $$ SELECT $1, CAST($1 AS text) || ' is text' $$ LANGUAGE SQL; SELECT * FROM dup(42); You can do the same thing more verbosely with an explicitly named composite type: CREATE TYPE dup_result AS (f1 int, f2 text); CREATE FUNCTION dup(int) RETURNS dup_result AS $$ SELECT $1, CAST($1 AS text) || ' is text' $$ LANGUAGE SQL; SELECT * FROM dup(42); Another way to return multiple columns is to use a TABLE function: CREATE FUNCTION dup(int) RETURNS TABLE(f1 int, f2 text) AS $$ SELECT $1, CAST($1 AS text) || ' is text' $$ LANGUAGE SQL; SELECT * FROM dup(42); However, a TABLE function is different from the preceding examples, because it actually returns a *set* of records, not just one record.

Back