Sub topic 4
What a SQL function returns
This chapter assumes you can write a basic CREATE FUNCTION ... LANGUAGE sql statement and know the difference between a scalar value, a row and a set of rows. It covers how PostgreSQL decides what a SQL function hands back to the caller, and the errors you get when the body and the declared type disagree.
The last statement rule
A SQL function body can hold several statements. PostgreSQL runs them in order and discards the results of all but the last. The result of the final statement is the result of the function.
The final statement must be one of these:
- A
SELECT(orVALUES, or aWITHquery ending in aSELECT). - An
INSERT,UPDATEorDELETEwith aRETURNINGclause. PostgreSQL 15 and later also acceptMERGE ... RETURNINGfrom version 17. - Any statement at all, if the function is declared
RETURNS void.
If the declared type is not void and the last statement produces no rows, PostgreSQL rejects the function. With the default check_function_bodies = on, a $$ body is checked when you create the function, so you see the error early.
On PostgreSQL 14 and later you can also write a single-expression body with RETURN:
CREATE FUNCTION double_it(n integer)
RETURNS integer
LANGUAGE sql
IMMUTABLE
RETURN n * 2;This is equivalent to a body of SELECT n * 2;.
Scalar results
A function declared with a base type such as integer, numeric or text must end with a statement that returns exactly one column of that type. The table below sets out what happens with the number of rows.
| Rows from the final statement | Scalar function result |
|---|---|
| Zero | `NULL` |
| One | That row's value |
| Several | The first row, discarding the rest |
"First" has no stable meaning without ORDER BY, so a scalar function that can see more than one row needs one. The setup below is used for the rest of the chapter.
CREATE TABLE products (
id integer PRIMARY KEY,
name text NOT NULL,
price numeric NOT NULL
);
INSERT INTO products VALUES
(1, 'Pen', 2.50),
(2, 'Notebook', 6.00),
(3, 'Backpack', 40.00);
CREATE FUNCTION cheapest_price()
RETURNS numeric
LANGUAGE sql
STABLE
AS $$
SELECT price FROM products ORDER BY price LIMIT 1;
$$;
CREATE FUNCTION product_price(p_id integer)
RETURNS numeric
LANGUAGE sql
STABLE
AS $$
SELECT price FROM products WHERE id = p_id;
$$;
SELECT cheapest_price(); -- 2.50
SELECT product_price(2); -- 6.00
SELECT product_price(999); -- NULL, because no row matchedThe last call does not raise an error. Zero rows become NULL, so a caller cannot tell "no such product" apart from a product whose price is NULL unless the column is NOT NULL, as it is here.
Type matching
The select list of the final statement must match the declared type. Too many or too few columns is an error, and so is a column of an incompatible type. A mismatch produces an error that starts with return type mismatch in function declared to return ..., followed by a detail line naming the actual type.
Add explicit casts when the types differ, even if PostgreSQL might accept an implicit one:
CREATE FUNCTION price_in_cents(p_id integer)
RETURNS integer
LANGUAGE sql
STABLE
AS $$
SELECT (price * 100)::integer FROM products WHERE id = p_id;
$$;Composite results
A function can return a whole row. The declared type is either the row type of an existing table, which every table has automatically, or a type you create with CREATE TYPE.
CREATE FUNCTION get_product(p_id integer)
RETURNS products
LANGUAGE sql
STABLE
AS $$
SELECT * FROM products WHERE id = p_id;
$$;
CREATE TYPE price_range AS (low numeric, high numeric);
CREATE FUNCTION product_price_range()
RETURNS price_range
LANGUAGE sql
STABLE
AS $$
SELECT min(price), max(price) FROM products;
$$;The final statement must return the same columns, in the same order, as the composite type. Names do not need to match, only positions and types.
How you call the function decides what you see:
SELECT product_price_range(); -- one column holding a row value: (2.50,40.00)
SELECT * FROM product_price_range(); -- two columns: low, high
SELECT (product_price_range()).high; -- 40.00
SELECT * FROM get_product(2); -- id, name, price as separate columnsIn the FROM form the function behaves like a one-row table. Prefer it to SELECT (f()).*. The (f()).* form expands to one field selection per column, and depending on the version and query shape the function may be evaluated once for each column.
The all-NULL row gotcha
When a composite-returning function finds no rows, the result is a NULL composite value. Selecting from it in FROM still produces one row, with every column NULL:
SELECT * FROM get_product(999);
-- id | name | price
-- ----+------+-------
-- | |If the caller needs to distinguish "not found" from a real row, test for it, or use a set-returning function (next chapter), which gives zero rows in that case. Because products.id is a primary key, id IS NULL on the result also tells you nothing was found.
Void results and side effects
A function declared RETURNS void returns nothing. The final statement may be anything, including an INSERT without RETURNING.
CREATE TABLE audit_log (at timestamptz DEFAULT now(), message text);
CREATE FUNCTION log_message(p_message text)
RETURNS void
LANGUAGE sql
AS $$
INSERT INTO audit_log (message) VALUES (p_message);
$$;
SELECT log_message('hello');SELECT log_message(...) returns one row with an empty value. If you only want the side effect and have no use for a result, a procedure with CALL is often clearer. Procedures are covered in a later chapter.
Returning the result of a data change
A function whose final statement is INSERT ... RETURNING returns what the RETURNING clause produces. With a scalar declaration, only the first returned row is passed back, but the statement still runs to completion:
CREATE TABLE tags (id serial PRIMARY KEY, label text);
CREATE FUNCTION add_tags(p_a text, p_b text)
RETURNS integer
LANGUAGE sql
AS $$
INSERT INTO tags (label) VALUES (p_a), (p_b)
RETURNING id;
$$;
SELECT add_tags('red', 'blue'); -- returns one id
SELECT count(*) FROM tags; -- 2, so both rows were insertedHere the function inserts two rows but reports only one id. If the caller needs all the ids, declare RETURNS SETOF integer instead.
OUT parameters and the implied record
When a function has OUT or INOUT parameters, they define the result columns, and you do not write a RETURNS clause for them. One output parameter makes a scalar. Several make an anonymous composite, and the final statement must produce columns matching them in order.
CREATE FUNCTION price_bounds(OUT low numeric, OUT high numeric)
LANGUAGE sql
STABLE
AS $$
SELECT min(price), max(price) FROM products;
$$;
SELECT * FROM price_bounds();Common errors
- Final statement is not a query. A function declared
RETURNS integerthat ends with a plainINSERTorUPDATEfails with a message that the final statement must be aSELECTor haveRETURNING. - Wrong column count. The final statement returns more columns than the composite type has, or fewer.
- Wrong column types. For example,
textwhereintegeris declared. Add a cast. - A parameter name that matches a column name. Inside the body, a column name wins over a parameter of the same name, so
WHERE id = idis always true. Prefix parameters (p_id) or writefunction_name.param. - Scalar function over many rows without
ORDER BY. The "first" row is arbitrary and can change between runs or after an index change.
Exercise
A function is declared RETURNS integer and its body is SELECT id FROM orders WHERE customer_id = $1;. Customer 7 has three orders, and customer 8 has none. What does the function return for each customer, and how would you make the result predictable for customer 7?
Show answer
For customer 7 it returns the id of the first row the query produces, and the other two rows are discarded. Without ORDER BY, which row that is can vary. For customer 8 it returns NULL, because zero rows become NULL for a scalar function. To make customer 7 predictable, add an ORDER BY (for example ORDER BY ordered_at DESC LIMIT 1 for the latest order). To return all three ids, declare the function RETURNS SETOF integer.
Exercise
Given get_product(p_id integer) RETURNS products, what does SELECT * FROM get_product(999); return when no product has id 999, and why?
Show answer
It returns one row in which every column is NULL. The function returns a NULL composite value when the final statement yields no rows, and a function in FROM always produces a row for that value. A set-returning function would give zero rows instead.