Sub topic 6
Returning rows with SETOF and RETURNS TABLE
This chapter covers functions that return zero, one or many rows instead of a single value. It assumes you can write a basic CREATE FUNCTION ... LANGUAGE sql statement, know that a SQL function returns the result of its last statement, and can read SELECT ... FROM ... JOIN queries. The examples use the two tables below.
CREATE TABLE customers (id int PRIMARY KEY, name text);
CREATE TABLE orders (
id int PRIMARY KEY,
customer_id int REFERENCES customers (id),
ordered_at timestamptz,
total numeric
);
INSERT INTO customers VALUES (1, 'Ada'), (2, 'Grace'), (3, 'Linus');
INSERT INTO orders VALUES
(10, 1, '2026-01-05', 40),
(11, 1, '2026-02-10', 25),
(12, 1, '2026-03-15', 90),
(13, 2, '2026-02-20', 15);The working model
A scalar function returns one value. If its last statement produces several rows, PostgreSQL silently returns only the first. A set-returning function declares that it returns many rows, and every row of the last statement becomes part of the result.
There are two ways to declare this:
RETURNS SETOF typereturns zero or more values of one type. The type can be a base type such asint, or a row type such as a table name.RETURNS TABLE (column definitions)returns rows with named, typed columns that you list yourself.
SETOF with an existing type
When the rows have the shape of a table, return SETOF that table's name.
CREATE FUNCTION orders_over(min_total numeric)
RETURNS SETOF orders
LANGUAGE sql
STABLE
AS $$
SELECT * FROM orders WHERE total > min_total ORDER BY id;
$$;
SELECT * FROM orders_over(30);The last statement must produce columns that match the orders row type in number, order and type. SELECT * works here, but it ties the function to the table definition. If someone later adds a column to orders, the function's result no longer matches. Listing the columns explicitly is no safer, because a changed column type breaks it the same way.
SETOF also works with scalar types. The function below returns one int per row.
CREATE FUNCTION order_ids(p_customer_id int)
RETURNS SETOF int
LANGUAGE sql
STABLE
AS $$
SELECT id FROM orders WHERE customer_id = p_customer_id ORDER BY id;
$$;
SELECT * FROM order_ids(1);The result has one column, and its name is the function name, order_ids. You can rename it with an alias: FROM order_ids(1) AS t(id).
RETURNS TABLE
RETURNS TABLE gives each output column a name and a type. This is the usual choice when the result is a projection or a computed shape that no table represents.
CREATE FUNCTION recent_orders(p_customer_id int, p_limit int DEFAULT 10)
RETURNS TABLE (order_id int, ordered_at timestamptz, total numeric)
LANGUAGE sql
STABLE
AS $$
SELECT o.id, o.ordered_at, o.total
FROM orders AS o
WHERE o.customer_id = p_customer_id
ORDER BY o.ordered_at DESC
LIMIT p_limit;
$$;
SELECT * FROM recent_orders(1, 2);The body's column names do not have to match the declared names. PostgreSQL matches columns by position and checks only their types. The declared names are what callers see.
RETURNS TABLE (...) is shorthand for declaring each column as an OUT parameter and returning SETOF record. The two functions below are equivalent in what they return.
CREATE FUNCTION order_totals_a(p_customer_id int)
RETURNS TABLE (order_id int, total numeric)
LANGUAGE sql
STABLE
AS $$
SELECT id, total FROM orders WHERE customer_id = p_customer_id;
$$;
CREATE FUNCTION order_totals_b(p_customer_id int, OUT order_id int, OUT total numeric)
RETURNS SETOF record
LANGUAGE sql
STABLE
AS $$
SELECT id, total FROM orders WHERE customer_id = p_customer_id;
$$;Without SETOF record, a function with OUT parameters returns exactly one row. RETURNS TABLE avoids that mistake because it always means a set.
| Declaration | Column names come from | Best when |
|---|---|---|
| `RETURNS SETOF orders` | The table's columns | The rows are whole rows of an existing table or composite type |
| `RETURNS SETOF int` | The function name | You need a list of single values |
| `RETURNS TABLE (a int, b text)` | The declaration | The result has a custom shape |
| `OUT` parameters plus `SETOF record` | The `OUT` parameters | You need `OUT` semantics, for example to mix with `INOUT` parameters |
Calling set-returning functions
Call a set-returning function in the FROM clause. It then behaves like a table, and you can filter, join and alias it.
SELECT order_id, total
FROM recent_orders(1, 5)
WHERE total > 30;You can also put one in the SELECT list. With SETOF over a row type, this returns a single composite column, not separate columns, and PostgreSQL expands the set into multiple rows. Prefer FROM, which gives you real columns and clearer semantics.
To number the rows, add WITH ORDINALITY. It appends a bigint column that counts from 1.
SELECT *
FROM recent_orders(1, 3) WITH ORDINALITY AS t(order_id, ordered_at, total, position);One call per row with LATERAL
A function in FROM can refer to columns of tables that appear before it. PostgreSQL treats this as an implicit LATERAL join, so the function runs once for each row on its left.
SELECT c.name, r.order_id, r.total
FROM customers AS c
CROSS JOIN LATERAL recent_orders(c.id, 2) AS r
ORDER BY c.name, r.ordered_at DESC;CROSS JOIN drops customers who have no orders, in this case Linus. To keep them, with NULLs in the function's columns, write LEFT JOIN LATERAL recent_orders(c.id, 2) AS r ON true.
Empty results and NULL
A set-returning function that finds no rows returns an empty set, not a NULL row. A scalar SQL function whose last statement finds no rows returns NULL. This difference matters when you decide between SETOF and a scalar return.
Common errors
Return type mismatch
PostgreSQL checks the last statement against the declared columns when you create the function, as long as check_function_bodies is on, which is the default. Suppose you declare n int but the body uses count(*). The CREATE FUNCTION fails with an error that begins return type mismatch in function declared to return record, with a detail line such as Final statement returns bigint instead of integer at column 2. Fix it by casting in the body or by declaring the column as bigint.
CREATE FUNCTION order_counts()
RETURNS TABLE (customer_id int, n bigint)
LANGUAGE sql
STABLE
AS $$
SELECT o.customer_id, count(*) FROM orders AS o GROUP BY o.customer_id;
$$;You get a similar error when the number of columns differs. PostgreSQL does not insert NULLs or drop extra columns for you.
Parameter names that match column names
In a SQL function body, a name that matches a column of a table in the query refers to the column, not the parameter. The following function compares a column with itself, so it returns every order that has a non-NULL customer_id.
CREATE FUNCTION orders_for_customer(customer_id int)
RETURNS SETOF orders
LANGUAGE sql
STABLE
AS $$
SELECT * FROM orders WHERE customer_id = customer_id;
$$;Two fixes work. The first is to qualify the parameter with the function name, as in orders_for_customer.customer_id. The second, and the more common one, is to use a naming convention such as the p_ prefix used throughout this chapter. Qualify table columns too, as in o.customer_id, so the intent stays clear.
The last statement decides the result
Only the final statement's rows are returned. A SELECT before it is run and thrown away. A set-returning function whose last statement is INSERT ... RETURNING also returns those rows, which a later chapter covers.
Performance notes
- A set-returning function in
FROMhas a default row estimate of 1000. A wrong estimate can lead the planner to a poor join strategy. TheROWSsetting, covered in a later chapter, corrects it. - A simple
LANGUAGE sqlfunction that returns a set may be inlined into the calling query, which lets the planner optimize across the boundary. The chapter on inlining explains when that happens. - Rows are produced as the query runs, but the function's result is fully built before the outer query reads it in many cases. For very large sets, filter inside the function or give it parameters that limit the rows.
Exercise
Write a function topcustomers(pmintotal numeric) that returns a table with columns customerid int and spent numeric. It lists each customer whose orders sum to more than pmintotal, largest sum first. Which declaration do you use, and how do you list the customers together with their names?
Show answer
Use RETURNS TABLE (customerid int, spent numeric) with LANGUAGE sql STABLE and the body SELECT o.customerid, sum(o.total) FROM orders AS o GROUP BY o.customerid HAVING sum(o.total) > pmintotal ORDER BY sum(o.total) DESC;. The sum of a numeric column is numeric, so the types match. Because the function returns only ids, join it in FROM to get names: SELECT c.name, t.spent FROM topcustomers(50) AS t JOIN customers AS c ON c.id = t.customer_id;