Sub topic 3
Parameters, defaults and OUT columns
This chapter assumes you can write a basic CREATE FUNCTION ... LANGUAGE sql statement and know how SELECT and INSERT work. You should also be comfortable with common PostgreSQL types and with running statements in psql. Here you will learn how to declare the inputs a function takes and the columns it returns, and how the two interact.
Named and positional parameters
A parameter is declared as an optional mode, an optional name, and a type. Naming parameters is optional, but you should almost always do it. A named parameter documents itself, and callers can pass it by name.
Inside a SQL function body you can refer to a parameter by name or by position ($1, $2, ...). Both forms are equivalent. Unnamed parameters can only be used positionally.
CREATE FUNCTION discounted(price numeric, pct numeric)
RETURNS numeric
LANGUAGE sql
IMMUTABLE
AS $$
SELECT price * (1 - pct / 100);
$$;
SELECT discounted(80, 25);
SELECT discounted(pct => 25, price => 80);Both calls return 60. The second call uses named notation, so the order of arguments does not matter.
Parameters can only stand in for values. You cannot use one as a table name, column name or keyword. For example, SELECT * FROM $1 is invalid in a SQL function. Dynamic identifiers need PL/pgSQL with EXECUTE.
When a parameter name matches a column name
A SQL function body is parsed as an ordinary query. If a parameter has the same name as a column of a table in the query, the column wins. The function then compiles without error but does the wrong thing.
-- Assumes a table accounts(id int primary key, balance numeric)
CREATE FUNCTION balance_wrong(id int)
RETURNS numeric
LANGUAGE sql
STABLE
AS $$
SELECT balance FROM accounts WHERE id = id;
$$;
CREATE FUNCTION balance_of(id int)
RETURNS numeric
LANGUAGE sql
STABLE
AS $$
SELECT balance FROM accounts WHERE accounts.id = balance_of.id;
$$;In balance_wrong, both id references mean the column. The condition is true for every row with a non-null id, so the function returns the balance of whichever row the query finds first. In balance_of, the table name qualifies the column and the function name qualifies the parameter.
Default values
Add DEFAULT expression (or = expression) after a parameter's type to make the argument optional.
CREATE FUNCTION format_price(
amount numeric,
currency text DEFAULT 'USD',
decimals int DEFAULT 2
)
RETURNS text
LANGUAGE sql
IMMUTABLE
AS $$
SELECT currency || ' ' || round(amount, decimals)::text;
$$;
SELECT format_price(1234.5); -- USD 1234.50
SELECT format_price(1234.5, 'EUR'); -- EUR 1234.50
SELECT format_price(1234.5, decimals => 0); -- USD 1235
SELECT format_price(amount => 9.99, currency => 'GBP');The rules for defaults:
- Every input parameter after one with a default must also have a default. This is why
currencyanddecimalsboth carry one. - A call can omit arguments only from the end when using positional notation. To skip
currencyand setdecimals, use named notation, as in the third call above. - You can mix styles, but positional arguments must come first:
format_price(1234.5, decimals => 0). - Defaults are evaluated when the function is called, not when it is created. A default such as
now()gives the call time. - Named notation accepts
=>(preferred) and the older:=.
Defaults interact badly with overloading (several functions with the same name). If you define f(int) and f(int, int DEFAULT 0), the call f(1) matches both and fails with "function f(integer) is not unique". Avoid overlapping signatures.
Parameter modes
Each parameter has a mode. If you omit it, the mode is IN.
| Mode | Direction | Part of the signature? | Part of the result? |
|---|---|---|---|
| `IN` | Caller to function | Yes | No |
| `OUT` | Function to caller | No | Yes |
| `INOUT` | Both | Yes | Yes |
| `VARIADIC` | Caller to function, as a variable-length list | Yes | No |
The signature is what identifies a function for overloading, DROP FUNCTION and GRANT. Only the input modes (IN, INOUT, VARIADIC) count toward it.
OUT parameters and result columns
OUT parameters let you declare the shape of the result next to the inputs, without a separate RETURNS clause.
-- Assumes a table products(category text, price numeric)
CREATE FUNCTION price_stats(
IN p_category text,
OUT min_price numeric,
OUT max_price numeric,
OUT item_count bigint
)
LANGUAGE sql
STABLE
AS $$
SELECT min(price), max(price), count(*)
FROM products
WHERE category = p_category;
$$;The return type is now a record with three columns. The body's last statement must produce columns that match them in number and type, in order. The names in the SELECT list do not matter. The OUT names become the column names.
How you call it determines how you see the result:
SELECT price_stats('books');
SELECT * FROM price_stats('books');
SELECT max_price FROM price_stats('books');The first query returns one column holding a composite value such as (4.50,39.00,128). The second and third expand the record into real columns. Use FROM for OUT functions in most cases.
Some details to remember:
- With a single
OUTparameter, the return type is just that parameter's type, not a record. - If you also write
RETURNS, it must agree with theOUTparameters. For severalOUTparameters it must beRETURNS record. Most code leavesRETURNSout. - The body must return a row. Since
price_statsuses aggregates, it always returns exactly one row, even when no products match (withNULL,NULLand0). - Because
OUTparameters are not in the signature,DROP FUNCTION price_stats(text);is enough. You may also include them.
INOUT
An INOUT parameter is an input and also a result column. The body can refer to it by name as an input.
CREATE FUNCTION bump(INOUT counter int, step int DEFAULT 1)
LANGUAGE sql
IMMUTABLE
AS $$
SELECT counter + step;
$$;
SELECT bump(10);
SELECT bump(10, 5);These return 11 and 15. There is one output column (counter), so the result is a plain integer.
Variable argument lists with VARIADIC
A VARIADIC parameter must be the last input parameter and must be an array type. Callers pass any number of values, which PostgreSQL collects into the array.
CREATE FUNCTION max_of(VARIADIC nums numeric[])
RETURNS numeric
LANGUAGE sql
IMMUTABLE
AS $$
SELECT max(n) FROM unnest(nums) AS n;
$$;
SELECT max_of(3, 9, 4);
SELECT max_of(VARIADIC ARRAY[3, 9, 4]::numeric[]);Both calls return 9. The second shows how to pass an existing array. Without the VARIADIC keyword at the call site, PostgreSQL would treat the array as a single element.
Common errors
- "input parameters after one with a default value must also have defaults". Give every later input parameter a default, or reorder the parameters.
- "cannot change name of input parameter".
CREATE OR REPLACE FUNCTIONcannot rename an input parameter. Drop and recreate the function, which means re-granting privileges and re-checking dependent objects. - "cannot change return type of existing function". Adding, removing or retyping
OUTparameters changes the result type, so replacement is refused. Drop and recreate. - "function is not unique". Two overloads both match the call, often because of defaults. Remove one or change the argument types.
- "function returning record called in context that cannot accept type record". You selected an
OUTfunction in a context that needs column names. UseSELECT * FROM fn(...). - Silently wrong results. Usually a parameter name that matches a column name, as shown earlier.
Exercise
Write a function order_summary(p_customer_id int, OUT order_count bigint, OUT total_spent numeric) for a table orders(id int, customer_id int, total numeric). Then explain how to call it so that the result appears as two columns, and what DROP FUNCTION line removes it.
Show answer
CREATE FUNCTION ordersummary(pcustomerid int, OUT ordercount bigint, OUT totalspent numeric) LANGUAGE sql STABLE AS $$ SELECT count(*), COALESCE(sum(total), 0) FROM orders WHERE customerid = pcustomerid; $$; Call it with SELECT * FROM ordersummary(42); so the record is expanded into ordercount and totalspent. SELECT ordersummary(42) would return a single composite column instead. Because OUT parameters are not part of the signature, DROP FUNCTION order_summary(int); removes it.