Sub topic 7
Returning Scalars, Rows, and Sets of Rows
This chapter assumes basic SQL, PostgreSQL data types, and PL/pgSQL block structure. You should also know how to run SELECT statements and create tables.
A PL/pgSQL function declares its result shape before its body. PostgreSQL uses that declaration to check the value returned by RETURN. Choose the smallest useful shape:
| Result shape | Declaration | Typical use |
|---|---|---|
| One value | `RETURNS numeric` | A calculation or lookup |
| One row | `RETURNS orders` | A complete table row |
| Many rows | `RETURNS TABLE (...)` | A filtered or transformed result set |
Returning one scalar value
A scalar is one value, such as an integer, date, or text value. A function with a scalar result uses RETURN followed by an expression.
CREATE FUNCTION add_tax(price numeric, rate numeric DEFAULT 0.2)
RETURNS numeric
LANGUAGE plpgsql
IMMUTABLE
AS $$
BEGIN
RETURN round(price * (1 + rate), 2);
END;
$$;
SELECT add_tax(100);
SELECT add_tax(100, rate => 0.07);The RETURNS type must match the expression returned by the function. A default parameter lets callers omit rate. The IMMUTABLE attribute states that the same inputs always produce the same output.
A function that performs a query usually stores the result in a variable with SELECT INTO:
CREATE FUNCTION customer_order_count(p_customer_id integer)
RETURNS bigint
LANGUAGE plpgsql
STABLE
AS $$
DECLARE
v_count bigint;
BEGIN
SELECT count(*) INTO v_count
FROM orders
WHERE customer_id = p_customer_id;
RETURN v_count;
END;
$$;SELECT INTO assigns the query result to a variable. count(*) always produces one row, including when no orders match.
Returning one row
A function can return a composite value, such as a row from the orders table. The result type must identify the row structure.
CREATE FUNCTION find_order(p_id integer)
RETURNS orders
LANGUAGE plpgsql
STABLE
AS $$
DECLARE
v_order orders;
BEGIN
SELECT * INTO v_order
FROM orders
WHERE id = p_id;
RETURN v_order;
END;
$$;If no row matches, the composite variable contains null fields unless you check FOUND or use INTO STRICT. INTO STRICT requires exactly one row and raises an error otherwise.
Returning a set of rows
A set-returning function produces zero or more rows. RETURNS TABLE names both the output columns and their types. RETURN QUERY appends all rows from a query to the function's 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 AS o
WHERE o.total > p_min
ORDER BY o.id;
END;
$$;
SELECT * FROM orders_over(500);The table alias o qualifies column names and prevents confusion between table columns, parameters, and output variables.
You can also build a set one row at a time with RETURN NEXT, but RETURN QUERY is usually clearer and faster for a query result. A final bare RETURN is optional when the function reaches its end.
Common mistakes
- Returning a table row with columns in the wrong order.
- Declaring
RETURNS TABLEtypes that do not match the query. - Forgetting that a set-returning function is queried with
SELECT * FROM function(...). - Using a loop to construct rows when one set-based
RETURN QUERYcan do the work. - Assuming ordinary
SELECT INTOraises an error when no row matches.
Exercise
Write a function named discounted_total that accepts a numeric total and returns the total multiplied by 0.9, rounded to two decimal places.
Show answer
Use RETURNS numeric and return round(p_total * 0.9, 2) from the function body.