Sub topic 4
Parameters: named, default, OUT, and INOUT
This chapter assumes you can already write a basic CREATE FUNCTION ... LANGUAGE plpgsql with a BEGIN ... END body and call it from psql. It covers how to declare parameters, how callers pass arguments, and how a function or procedure sends values back through its parameter list.
Parameter modes
Each parameter has a mode. If you write no mode, PostgreSQL uses IN.
| Mode | Caller supplies a value | Value returned to caller | Notes |
|---|---|---|---|
| `IN` | Yes | No | The default. Behaves like a read-only variable in the body. |
| `OUT` | No | Yes | Starts as `NULL`. Assign to it in the body. |
| `INOUT` | Yes | Yes | Holds the input value at start. Assign to it to change the result. |
| `VARIADIC` | Yes, zero or more values | No | Must be last. The body sees a single array. |
Inside the body, every parameter is an ordinary variable. You can read it, and you can assign to it with :=. Assigning to an IN parameter is legal in PL/pgSQL, but the change is invisible to the caller.
Named parameters
Give every parameter a name. Positional access through $1 and $2 still works, but names make the body and the calls much easier to read.
CREATE FUNCTION format_price(
amount numeric,
currency text DEFAULT 'EUR',
decimals integer DEFAULT 2
)
RETURNS text
LANGUAGE plpgsql
IMMUTABLE
AS $$
BEGIN
RETURN currency || ' ' || round(amount, decimals)::text;
END;
$$;A caller can pass arguments in three ways.
-- Positional: matched by order
SELECT format_price(1234.5, 'USD', 0);
-- Named: matched by name, in any order
SELECT format_price(decimals => 1, amount => 1234.5);
-- Mixed: positional arguments first, then named ones
SELECT format_price(1234.5, decimals => 0);The named form accepts => (preferred) and the older :=. In mixed notation, every positional argument must come before the first named one. After a named argument, you cannot go back to positional.
Default values
A default is declared with DEFAULT or =, and PostgreSQL uses it when the caller omits that argument.
SELECT format_price(1234.5);
SELECT format_price(1234.5, 'USD');
SELECT format_price(1234.5, decimals => 0);These return EUR 1234.50, USD 1234.50, and EUR 1235.
Two rules apply to defaults:
- Once an input parameter has a default, every input parameter after it must also have one.
OUTparameters are exempt from this check. - In positional notation, a caller can only omit trailing arguments. To skip a middle one, use named notation, as the
decimals => 0call above does.
Named notation cannot skip a parameter that has no default. This call fails because amount is required.
SELECT format_price(currency => 'USD');
-- ERROR: function format_price(currency => unknown) does not existThe error says the function "does not exist", not that an argument is missing. The cause is that no function matches that set of named arguments.
The following diagram shows how PostgreSQL fills in the arguments of a call.
OUT parameters
An OUT parameter lets a function return several values without declaring a composite type. When a function has more than one OUT parameter, PostgreSQL makes it return a record. You do not write a RETURNS clause.
CREATE FUNCTION price_breakdown(
IN gross numeric,
IN rate numeric DEFAULT 0.2,
OUT net numeric,
OUT tax numeric
)
LANGUAGE plpgsql
IMMUTABLE
AS $$
BEGIN
net := round(gross / (1 + rate), 2);
tax := gross - net;
END;
$$;
SELECT * FROM price_breakdown(120);The result has one row with the columns net and tax, with values 100.00 and 20.00. The body has no RETURN statement. When the body ends, PostgreSQL returns the current values of the OUT variables. A bare RETURN; also works if you want to leave early.
With exactly one OUT parameter, the function returns that parameter's type directly, as a plain scalar.
Call OUT functions in the FROM clause with SELECT * FROM. That expands the columns by name. If you write SELECT price_breakdown(120), you get a single composite value that looks like (100.00,20.00).
If you also write RETURNS, it must agree with the OUT list. For a single OUT parameter, RETURNS must name its type. For several, it must be RETURNS record. Leaving RETURNS out is the cleaner choice.
INOUT parameters
An INOUT parameter is both an argument and a result column. The caller passes a value, the body can change it, and the changed value comes back.
CREATE FUNCTION clamp_quantity(
INOUT qty integer,
IN max_qty integer DEFAULT 100
)
LANGUAGE plpgsql
IMMUTABLE
AS $$
BEGIN
qty := least(greatest(qty, 0), max_qty);
END;
$$;
SELECT clamp_quantity(250);
SELECT clamp_quantity(-5);
SELECT clamp_quantity(qty => 40, max_qty => 30);The results are 100, 0, and 30. The output column is named qty, after the INOUT parameter.
Parameters in procedures
Procedures use the same syntax, but a procedure has no RETURNS clause. Its only way to send values back is through INOUT parameters. From PostgreSQL 14, procedures also accept OUT parameters. CALL returns one row holding the INOUT and OUT values.
CREATE PROCEDURE apply_discount(
INOUT price numeric,
IN pct numeric DEFAULT 10
)
LANGUAGE plpgsql
AS $$
BEGIN
price := round(price * (1 - pct / 100), 2);
END;
$$;
CALL apply_discount(80);
CALL apply_discount(price => 80, pct => 25);The two calls return 72.00 and 60.00. In plain SQL, pass a literal or expression for each INOUT argument. Inside PL/pgSQL, the INOUT argument must be a variable, and the call assigns the result back to it.
DO $$
DECLARE
v_price numeric := 80;
BEGIN
CALL apply_discount(v_price, 25);
RAISE NOTICE 'discounted price: %', v_price;
END;
$$;This prints discounted price: 60.00.
Variadic parameters
A VARIADIC parameter collects any number of trailing arguments into an array. It must be the last input parameter.
CREATE FUNCTION max_of(VARIADIC nums numeric[])
RETURNS numeric
LANGUAGE plpgsql
IMMUTABLE
AS $$
BEGIN
RETURN (SELECT max(n) FROM unnest(nums) AS n);
END;
$$;
SELECT max_of(3, 9, 4);
SELECT max_of(VARIADIC ARRAY[3, 9, 4]);Both calls return 9. The second form passes an existing array through unchanged.
Name clashes with columns
A parameter name can collide with a column name inside a query in the body. PL/pgSQL refuses to guess which one you mean.
CREATE FUNCTION customer_email(id integer)
RETURNS text
LANGUAGE plpgsql
STABLE
AS $$
BEGIN
-- WHERE id = id would raise: column reference "id" is ambiguous
RETURN (
SELECT c.email
FROM customers c
WHERE c.id = customer_email.id
);
END;
$$;You have three ways to avoid the clash. The first is to qualify the parameter with the function name, as above. The second is to qualify every column with a table alias. The third is to use a prefix such as p_ for parameters, which is the most common convention. A prefix also changes the argument name callers see, so pick it before the function is published.
The same clash can happen with OUT parameters and RETURNS TABLE columns, because those names are variables too. The #variable_conflict directive can change how clashes resolve. Treat that as a last resort, because explicit qualification is easier to read.
Changing a signature later
CREATE OR REPLACE FUNCTION has limits on what it can change:
- You cannot rename an input parameter. PostgreSQL raises
cannot change name of input parameter. - You cannot change the return type or the
OUTparameters. PostgreSQL raisescannot change return type of existing function. - You cannot remove a default. PostgreSQL raises
cannot remove parameter defaults from existing function.
For these changes, run DROP FUNCTION first and then CREATE FUNCTION. Dropping breaks any dependent objects, such as views, triggers, and other functions that call it. Check the dependencies before you drop.
A function's identity is its name plus its input argument types. Adding a parameter with a default creates a new function. It does not replace the old one.
Exercises
Exercise
You write CREATE FUNCTION f(a integer DEFAULT 1, b integer) .... What happens, and how do you fix it?
Show answer
PostgreSQL rejects it with an error saying that an input parameter after one with a default must also have a default. Either give b a default too, or move a after b. A fix such as f(b integer, a integer DEFAULT 1) lets callers omit a.
Exercise
Write a function split_name(INOUT full_name text, OUT first_name text, OUT last_name text) that splits on the first space. What does SELECT * FROM split_name('Ada Lovelace') return, and what is the column list?
Show answer
One approach is first_name := split_part(full_name, ' ', 1); last_name := substr(full_name, strpos(full_name, ' ') + 1); in a PL/pgSQL body. The query returns one row with three columns, full_name, first_name, and last_name, holding Ada Lovelace, Ada, and Lovelace. The INOUT parameter comes back unchanged because the body never assigns to it.