Sub topic 2
Your first function: CREATE FUNCTION and the block structure
This chapter assumes you can write basic SQL (SELECT, INSERT, UPDATE, DELETE, JOIN), know common PostgreSQL data types, and can run statements in psql or another SQL client. It also assumes you know what variables, conditionals, and loops are. You do not need any prior PL/pgSQL.
What you will build
By the end of this chapter you can write a small PL/pgSQL function, explain every part of its definition, call it in several ways, and avoid the mistakes that most often trip up people on their first function.
The shape of CREATE FUNCTION
A function definition has two layers. The outer layer is a SQL command, CREATE FUNCTION. It tells PostgreSQL the function's name, its parameters, its return type, and which language the body is written in. The inner layer is the body, which is a string of PL/pgSQL code.
Here is a minimal function. It adds tax to a price.
CREATE FUNCTION add_tax(price numeric, rate numeric DEFAULT 0.2)
RETURNS numeric
LANGUAGE plpgsql
IMMUTABLE
AS $$
BEGIN
RETURN round(price * (1 + rate), 2);
END;
$$;
SELECT add_tax(100);
SELECT add_tax(100, rate => 0.07);The first call returns 120.00. The second returns 107.00. Read the definition from top to bottom:
CREATE FUNCTION add_tax(...)names the function and lists its parameters. Each parameter has a name and a type.ratehas a default value, so callers may leave it out.RETURNS numericdeclares the type of the value the function gives back.LANGUAGE plpgsqlselects the language used for the body. PL/pgSQL is installed and enabled by default in current PostgreSQL versions.IMMUTABLEis a volatility marker. It promises that the same inputs always give the same output and that the function reads no table data. Later chapters cover it in detail.AS $$ ... $$holds the body.
The clauses after the parameter list (RETURNS, LANGUAGE, IMMUTABLE, AS) can appear in any order. The convention of putting AS last keeps the long body at the bottom, where it is easy to find.
Why the body is a string
PostgreSQL does not parse the body when it reads the CREATE FUNCTION command. It receives the body as one string literal and hands that string to the language handler, which here is PL/pgSQL. This is why the body sits between quote marks.
Single quotes would work, but the body usually contains single quotes of its own, for example in string literals. You would have to double each one. Dollar quoting avoids this. A dollar-quoted string starts with $$ (or $tag$) and ends with the same marker. Anything between the markers is taken literally.
CREATE FUNCTION greeting(p_name text)
RETURNS text
LANGUAGE plpgsql
AS $body$
BEGIN
RETURN 'Hello, ' || p_name || '! It''s good to see you.';
END;
$body$;Using a tag such as $body$ lets you write $$ inside the body without ending the string early. This matters when a function body contains another dollar-quoted string, which happens with dynamic SQL later in the tutorial. Pick the tag, then use the same tag at both ends.
The block structure
A PL/pgSQL body is a block. A block has up to three parts:
[ DECLARE
declarations ]
BEGIN
statements
[ EXCEPTION
handlers ]
END;DECLAREis optional. It lists local variables. The next chapter covers it.BEGIN ... END;is required. The statements run in order.EXCEPTIONis optional. It catches errors raised inside the block. A later chapter covers it.
Every statement inside a block ends with a semicolon, including the final END;. The BEGIN here is not the SQL command BEGIN that starts a transaction. It only marks the start of a block of statements. This is a common source of confusion. A PL/pgSQL block does not start or end a transaction.
Blocks can nest. An inner block can have its own DECLARE section, and variables declared there are visible only inside it.
CREATE FUNCTION nested_demo()
RETURNS text
LANGUAGE plpgsql
AS $$
DECLARE
v_label text := 'outer';
BEGIN
DECLARE
v_label text := 'inner';
BEGIN
RAISE NOTICE 'inside: %', v_label;
END;
RETURN v_label;
END;
$$;
SELECT nested_demo();The RAISE NOTICE line prints inside: inner, and the function returns outer. The inner v_label hides the outer one while the inner block runs. Shadowing like this is legal but easy to misread, so avoid it in real code.
Calling a function
A function is called from inside a SQL expression. The simplest call is a SELECT with no FROM clause.
SELECT add_tax(100);You can also use a function anywhere a value is allowed, such as in a WHERE clause or a select list over a table:
SELECT id, total, add_tax(total) AS total_with_tax
FROM orders
WHERE add_tax(total) > 500;Here add_tax runs once per row for each place it appears. Keep that in mind when a function is slow, since it multiplies with the number of rows.
Positional and named arguments
PostgreSQL accepts three ways to pass arguments:
| Notation | Example | Notes |
|---|---|---|
| Positional | `add_tax(100, 0.07)` | Arguments match parameters by order. |
| Named | `add_tax(price => 100, rate => 0.07)` | Order does not matter. Clearer for functions with many parameters. |
| Mixed | `add_tax(100, rate => 0.07)` | Positional arguments must come first. |
The older := form (rate := 0.07) still works, but => is the standard spelling and is preferred.
Because rate has a default, add_tax(100) is valid. In a parameter list, once one parameter has a default, every parameter after it must also have one.
Replacing and dropping functions
Running CREATE FUNCTION twice with the same name and parameter types fails with an error saying the function already exists. Use CREATE OR REPLACE FUNCTION to redefine it:
CREATE OR REPLACE FUNCTION add_tax(price numeric, rate numeric DEFAULT 0.2)
RETURNS numeric
LANGUAGE plpgsql
IMMUTABLE
AS $$
BEGIN
RETURN round(price * (1 + rate), 2);
END;
$$;CREATE OR REPLACE has limits. You cannot change the return type or the names of input parameters this way. For those changes, drop the function first:
DROP FUNCTION add_tax(numeric, numeric);The drop command identifies the function by name and parameter types, not just name. This brings up an important rule.
Overloading: the signature is name plus types
PostgreSQL identifies a function by its name together with its input parameter types. Two functions can share a name if their parameter types differ. This is called overloading.
CREATE FUNCTION describe(p integer)
RETURNS text
LANGUAGE sql
AS $$ SELECT 'integer: ' || p $$;
CREATE FUNCTION describe(p text)
RETURNS text
LANGUAGE sql
AS $$ SELECT 'text: ' || p $$;
SELECT describe(42);
SELECT describe('abc');The first call returns integer: 42 and the second returns text: abc.
Overloading creates a trap when you change a signature. Suppose you add a third parameter to add_tax and run CREATE OR REPLACE. PostgreSQL treats this as a new function, because the types differ. The old two-parameter version stays in place. Calls then pick one or the other, or fail with an "ambiguous" error if both match. When you change a signature, drop the old version on purpose.
Common first-function errors
- Parameter names clash with column names. If a parameter is named
idand a query inside the function uses a columnid, PL/pgSQL raises an ambiguity error. The usual fix is a naming convention. This tutorial prefixes parameters withp_and local variables withv_. - Missing
RETURN. A function that declares a return type but reachesENDwithout aRETURNfails at run time with the message "control reached end of function without RETURN". - Forgetting the semicolon after
END. The body is parsed as a block, soEND;needs its semicolon. The semicolon after the closing$$ends theCREATE FUNCTIONcommand. - Unbalanced quote markers. If you open the body with
$body$and close with$$, the command never ends and psql keeps waiting for input. - Expecting a block to control transactions. The
BEGINandENDof a block do not commit or roll back anything. The function runs inside the transaction of its caller.
Checking what you created
In psql, two commands help you inspect functions:
\df add_taxlists functions with that name and shows their argument and result types.\sf add_taxprints the full source of the function so you can read it back.
From plain SQL, you can query the catalog:
SELECT proname, pg_get_function_arguments(oid) AS args, prorettype::regtype AS returns
FROM pg_proc
WHERE proname = 'add_tax';This returns one row per overload, which makes it a quick way to find leftover versions of a function after a signature change.
Summary of the working model
A function is a named, typed, stored piece of code. CREATE FUNCTION registers it in the database. The body is a string that PL/pgSQL parses as a block. The block runs when a SQL statement calls the function, inside that statement's transaction, and returns a value of the declared type. Next, you will add local variables to the DECLARE section.
Exercise
You run CREATE OR REPLACE FUNCTION addtax(price numeric, rate numeric, country text) with a new third parameter, but the original two-parameter addtax still exists. Why, and how do you remove the old one?
Show answer
A function is identified by its name plus its input parameter types. Adding a third parameter changes the types, so PostgreSQL creates a separate overload instead of replacing the old function. Remove the old one with DROP FUNCTION add_tax(numeric, numeric);
Exercise
Write a function named fullname that takes pfirst and p_last (both text) and returns them joined by a single space as text. Then call it using named arguments in reverse order.
Show answer
CREATE FUNCTION fullname(pfirst text, plast text) RETURNS text LANGUAGE plpgsql IMMUTABLE AS $$ BEGIN RETURN pfirst || ' ' || plast; END; $$; Then call it with: SELECT fullname(plast => 'Lovelace', pfirst => 'Ada'); which returns Ada Lovelace.
Exercise
A function declared RETURNS integer has a body of BEGIN PERFORM 1; END; and no RETURN statement. What happens when you call it, and when is the problem detected?
Show answer
The function is created without error, because PL/pgSQL does not check for a missing RETURN at creation time. The call fails at run time with the error "control reached end of function without RETURN".