Sub topic 2
Your first function: CREATE FUNCTION and the block structure
This chapter assumes you can write basic SQL, understand PostgreSQL data types, and run statements in psql or another SQL client. You should also know basic programming ideas such as parameters and return values.
A PL/pgSQL function is named logic stored in PostgreSQL. The database runs it when a query calls it. Use PL/pgSQL when the operation needs several SQL statements, conditions, loops, or error handling. If one SQL statement is enough, plain SQL is often simpler and easier for PostgreSQL to optimize.
The structure of a function
A function declaration has several parts:
CREATE FUNCTIONgives the function its name and parameters.RETURNSdeclares the result type.LANGUAGE plpgsqlselects the PL/pgSQL language.ASintroduces the function body.- The body contains a PL/pgSQL block.
The outer block has this shape:
[DECLARE
local declarations]
BEGIN
statements
END;DECLARE is optional. BEGIN and END mark the function's executable block. The BEGIN keyword here does not start a transaction. It starts a group of PL/pgSQL statements.
Build a small function
The following function calculates a price after tax. The rate parameter has a default value, so callers can omit it.
CREATE FUNCTION add_tax(price numeric, rate numeric DEFAULT 0.2)
RETURNS numeric
LANGUAGE plpgsql
IMMUTABLE
AS $func$
BEGIN
RETURN round(price * (1 + rate), 2);
END;
$func$;
SELECT add_tax(100);
SELECT add_tax(100, rate => 0.07);The first call uses the default rate of 0.2, returning 120.00. The second call uses a named argument and returns 107.00.
The RETURN statement ends this invocation and supplies the value promised by RETURNS numeric. Every possible execution path must return a compatible value. A function declared with RETURNS numeric cannot return a table or a text value.
$func$ is dollar quoting. It lets you write the function body without escaping every single quote inside it. The tag is arbitrary, but the opening and closing tags must match. The more common $$ tag also works.
IMMUTABLE tells PostgreSQL that the result depends only on the input values and does not change. This arithmetic function meets that promise. Do not use IMMUTABLE for a function that reads a table, checks the current time, or depends on database state.
Add declarations when needed
A function can declare local variables between DECLARE and BEGIN:
CREATE FUNCTION discounted_price(p_price numeric, p_discount numeric)
RETURNS numeric
LANGUAGE plpgsql
AS $$
DECLARE
final_price numeric;
BEGIN
final_price := p_price * (1 - p_discount);
RETURN round(final_price, 2);
END;
$$;The assignment operator in PL/pgSQL is :=. The variable exists only while the function runs. Later chapters cover variable types, queries, and control flow in more detail.
Use CREATE OR REPLACE FUNCTION when changing an existing function's body. PostgreSQL identifies a function by its name and input argument types, so changing those types can create a different function rather than replace the original.
Exercise
What does BEGIN mean inside a PL/pgSQL function, and why does the example mark add_tax as IMMUTABLE?
Show answer
BEGIN starts the function's executable block, not a transaction. add_tax is IMMUTABLE because its result depends only on its numeric inputs and deterministic arithmetic.