You mix syntax to return SETOF values ββwith syntax to return a single row or value .
- A related question: how to return a single record 'r' from
When you declare a function using RETURNS TABLE , you must use RETURN NEXT in the body to return a string (or scalar value). And if you want to use the record variable so that it must match the return type. See Code Examples below.
Returns a single value or string
If you just want to return a single row, there is no need for an undefined entry. @Kevin has already demonstrated two ways. I will add a simplified version with OUT parameters:
CREATE OR REPLACE FUNCTION my_func(OUT a integer, OUT b text) AS $func$ BEGIN a := ...; b := ...; END $func$ LANGUAGE plpgsql;
You do not even need to add RETURN; to the function body, the value of the declared OUT parameters will be automatically returned at the end of the function - NULL for any parameter that has not been assigned.
And you do not need to declare RETURNS RECORD , because it is already visible from the OUT parameters.
Returns a rowset
If you really want to return multiple rows (including the option for 0 or 1 rows), you can define the return type as RETURNS ...
SETOF some_type , where some_type can be any registered scalar or composite type.
TABLE (col1 type1, col2 type2) - ad-hoc type definition.
SETOF record plus OUT parameters for determining column names and types.
100% equivalent to RETURNS TABLE .
SETOF record without further definition. But then the returned rows are undefined , and you need to include a column definition list with each call (see Example).
Record Type Guide :
Writing variables is similar to string type variables, but they have no predefined structure. They take the actual row structure of the string that they assign during the SELECT or FOR command.
There is more, read the manual.
You can use a record variable without assigning a specific type, you can even return such records undefined:
CREATE OR REPLACE FUNCTION my_func() RETURNS SETOF record AS $func$ DECLARE r record; BEGIN r := (1::int, 'foo'::text); RETURN NEXT r;
Call:
SELECT * FROM my_func() AS x(a int, b text);
But this is very cumbersome as you need to provide a list of column definitions with every call. Usually it can be replaced with something more elegant:
- If you know the type at the time the function was created, declare it immediately (
RETURNS TABLE or friends).
CREATE OR REPLACE FUNCTION my_func() RETURNS SETOF tbl_or_type AS $func$ DECLARE r tbl_or_type; BEGIN SELECT INTO tbl_or_type * FROM tbl WHERE id = 10; RETURN NEXT r;
- If you know the type during a function call, there are more elegant ways to use polymorphic types :
Refactoring the PL / pgSQL function to return the output of various SELECT queries
In your question it is not clear what you need.