Sub topic 7
Returning scalars, rows, and sets of rows
This chapter explains how a PL/pgSQL function hands results back to its caller. You choose a return form in the RETURNS clause, and that choice decides how you write the body and how callers use the function. It assumes you can write a basic function with CREATE FUNCTION, declare variables, and run SELECT ... INTO.
The examples use these two tables:
CREATE TABLE customers (
id integer PRIMARY KEY,
name text NOT NULL,
email text
);
CREATE TABLE orders (
id integer PRIMARY KEY,
customer_id integer NOT NULL REFERENCES customers (id),
total numeric NOT NULL,
created_at date NOT NULL DEFAULT current_date
);
INSERT INTO customers VALUES (1, 'Ada', '[email protected]'), (2, 'Grace', '[email protected]');
INSERT INTO orders VALUES
(1, 1, 250.00, '2026-01-10'),
(2, 1, 900.00, '2026-02-03'),
(3, 2, 120.00, '2026-02-15');The four return forms
Every function declares one of these shapes.
| Form | `RETURNS` clause | Caller gets | Body ends with |
|---|---|---|---|
| Scalar | `RETURNS numeric` | One value | `RETURN expr;` |
| Row | `RETURNS orders` or `RETURNS record` | One composite value | `RETURN row_variable;` |
| Set | `RETURNS SETOF orders` or `RETURNS TABLE (...)` | Zero or more rows | `RETURN QUERY` or `RETURN NEXT`, then `RETURN;` |
| Nothing | `RETURNS void` | A void value | No `RETURN` value |
The diagram shows how to pick one.
Scalars
A scalar function returns one value of one type. Run the query into a variable and return it.
CREATE FUNCTION order_count(p_customer_id integer)
RETURNS bigint
LANGUAGE plpgsql
STABLE
AS $$
DECLARE
v_count bigint;
BEGIN
SELECT count(*) INTO v_count
FROM orders o
WHERE o.customer_id = p_customer_id;
RETURN v_count;
END;
$$;
SELECT order_count(1);The type of the RETURN expression must convert to the declared type. If execution reaches the end of the body without a RETURN, PostgreSQL raises control reached end of function without RETURN at run time. The error appears when a code path misses the RETURN, not when you create the function. This happens often with IF branches that each return but have no final RETURN after them.
RETURNS void is for functions called only for their side effects. Calling one with SELECT my_func(); returns a single empty-looking row.
A single row
When the result is one row with several columns, you have three choices.
Return an existing row type
Every table defines a composite type with the same name. A function can return it, and the declared variable can hold a whole row:
CREATE FUNCTION get_order(p_id integer)
RETURNS orders
LANGUAGE plpgsql
STABLE
AS $$
DECLARE
r orders;
BEGIN
SELECT * INTO r FROM orders WHERE id = p_id;
IF NOT FOUND THEN
RAISE EXCEPTION 'order % not found', p_id;
END IF;
RETURN r;
END;
$$;
SELECT * FROM get_order(2);The IF NOT FOUND check matters. Without it, a missing id leaves r with all fields NULL. The function would then return a row of nulls, which looks like a real row to the caller.
Return OUT parameters
OUT parameters define the output columns. The function then returns an anonymous record with those columns, and you assign to the parameters instead of writing RETURN expr.
CREATE FUNCTION order_stats(
p_customer_id integer,
OUT n bigint,
OUT biggest numeric
)
LANGUAGE plpgsql
STABLE
AS $$
BEGIN
SELECT count(*), max(o.total)
INTO n, biggest
FROM orders o
WHERE o.customer_id = p_customer_id;
END;
$$;
SELECT * FROM order_stats(1);Return `record`
RETURNS record gives you a row without naming its columns. The caller must then supply a column definition list, for example SELECT * FROM f() AS t(a int, b text). This is rarely worth it. Prefer OUT parameters or RETURNS TABLE, which describe the shape in the function itself.
Calling a row-returning function
Call it in the FROM clause to get separate columns:
SELECT * FROM order_stats(1);returns columnsnandbiggest.SELECT order_stats(1);returns one column holding a composite value such as(2,900.00).
Sets of rows
A set-returning function can appear in FROM like a table. There are two spellings: RETURNS SETOF some_type and RETURNS TABLE (...). They behave the same way. RETURNS TABLE is equivalent to declaring the same columns as OUT parameters with RETURNS SETOF record.
RETURN QUERY
RETURN QUERY runs a query and appends all its rows to the result:
CREATE FUNCTION orders_over(p_min numeric)
RETURNS TABLE (order_id integer, total numeric)
LANGUAGE plpgsql
STABLE
AS $$
BEGIN
RETURN QUERY
SELECT o.id, o.total
FROM orders o
WHERE o.total > p_min
ORDER BY o.id;
END;
$$;
SELECT * FROM orders_over(500);The query's columns must match the declared columns in number and in type, matched by position. A mismatch fails with an error such as structure of query does not match function result type. A numeric column where integer is declared also fails, so add a cast when needed.
RETURN NEXT
RETURN NEXT emits one row at a time. Use it when each row needs procedural logic. You assign values to the output variables, then emit the row:
CREATE FUNCTION spend_tiers()
RETURNS TABLE (customer_id integer, spend numeric, tier text)
LANGUAGE plpgsql
STABLE
AS $$
DECLARE
r record;
BEGIN
FOR r IN
SELECT o.customer_id AS cid, sum(o.total) AS s
FROM orders o
GROUP BY o.customer_id
ORDER BY o.customer_id
LOOP
customer_id := r.cid;
spend := r.s;
tier := CASE
WHEN r.s >= 1000 THEN 'gold'
WHEN r.s >= 500 THEN 'silver'
ELSE 'bronze'
END;
RETURN NEXT;
END LOOP;
RETURN;
END;
$$;
SELECT * FROM spend_tiers();For a function declared RETURNS SETOF orders, which has no output variables, you pass the row to RETURN NEXT some_row_variable; instead.
Ending a set-returning function
RETURN QUERY and RETURN NEXT do not leave the function. Execution continues with the next statement. A bare RETURN; ends the function and hands back everything collected so far. If the body just runs to END, the function also ends normally, and the final RETURN; is optional. A function that emits nothing returns an empty set, which is not an error and not a NULL row.
Memory behavior
PL/pgSQL does not stream rows to the caller as they are produced. RETURN NEXT and RETURN QUERY collect the whole result in a tuplestore, and the caller sees rows only after the function finishes. The store spills to disk once it exceeds work_mem, so memory use stays bounded. Very large sets still cost time and temporary disk space, and a caller that wants only the first 10 rows still waits for all of them. When the result is a single query with no procedural logic, a plain SQL function (LANGUAGE sql) can often be inlined into the calling query, which avoids this cost.
Choosing and checking a return form
Several mistakes recur with return types:
- Wrong call style.
SELECT f();on a set-returning function works, butSELECT * FROM f();is clearer and lets you filter, join, and order the result. - Silent null rows. A
RETURNS ordersfunction that selects into a row variable returns all-null fields when nothing matched. CheckFOUNDor useSELECT ... INTO STRICT. - Column mismatch. The
RETURN QUERYcolumn list must match the declared types. Check types with\df+ function_nameand by running the inner query on its own. - Changing a return type.
CREATE OR REPLACE FUNCTIONcannot change the return type or theOUTcolumns. Drop the function and create it again. Then recreate any dependent views or functions. - A
NULLscalar is not an empty set. A scalar function always returns exactly one value, possiblyNULL. Only set-returning functions can return zero rows.
Exercise
Write a function toporders(pcustomerid integer, plimit integer) that returns the customer's largest orders as a table with columns order_id and total, highest total first. Which return form and which return statement fit, and why must you alias the orders table in the query?
Show answer
Use RETURNS TABLE (orderid integer, total numeric) with a single RETURN QUERY, since the result is a set of rows and no per-row procedural logic is needed. The body is: RETURN QUERY SELECT o.id, o.total FROM orders o WHERE o.customerid = pcustomerid ORDER BY o.total DESC, o.id LIMIT plimit; The alias o is needed because orderid and total are also variables inside the function. An unqualified total would raise an ambiguity error. Calling SELECT * FROM top_orders(1, 1); returns order 2 with total 900.00.
Exercise
A function declared RETURNS SETOF orders contains "IF pall THEN RETURN QUERY SELECT FROM orders; END IF; RETURN QUERY SELECT FROM orders WHERE total > 500;". What does it return when pall is true, and how do you fix it?
Show answer
It returns every order followed by the orders over 500, so some rows appear twice. RETURN QUERY appends rows but does not leave the function. Fix it by adding RETURN; after the first RETURN QUERY inside the IF, or by moving the second RETURN QUERY into an ELSE branch.