Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL function return-type: TABLE vs SETOF records

What's the difference between a function that returns TABLE vs SETOF records, all else equal.

CREATE FUNCTION events_by_type_1(text) RETURNS TABLE(id bigint, name text) AS $$     SELECT id, name FROM events WHERE type = $1; $$ LANGUAGE SQL STABLE;  CREATE FUNCTION events_by_type_2(text) RETURNS SETOF record AS $$     SELECT id, name FROM events WHERE type = $1; $$ LANGUAGE SQL STABLE; 

These functions seem to return the same results. See this SQLFiddle.

like image 562
ma11hew28 Avatar asked Mar 15 '14 12:03

ma11hew28


People also ask

Can a PostgreSQL function return a table?

PostgreSQL returns a table with one column that holds the array of films. In practice, you often process each individual row before appending it in the function's result set.

Can function return multiple rows in SQL?

Alternatively, an SQL function can be declared to return a set (that is, multiple rows) by specifying the function's return type as SETOF sometype , or equivalently by declaring it as RETURNS TABLE( columns ) . In this case all rows of the last query's result are returned.

Which function is used to execute query in PostgreSQL?

To do this in PL/pgSQL, use the PERFORM statement: PERFORM query ; This executes query and discards the result. Write the query the same way you would write an SQL SELECT command, but replace the initial keyword SELECT with PERFORM .


1 Answers

When returning SETOF record the output columns are not typed and not named. Thus this form can't be used directly in a FROM clause as if it was a subquery or a table.

That is, when issuing:

SELECT * from events_by_type_2('social'); 

we get this error:

ERROR: a column definition list is required for functions returning "record"

It can be "casted" into the correct column types by the SQL caller though. This form does work:

SELECT * from events_by_type_2('social') as (id bigint, name text); 

and results in:

  id |      name       ----+----------------   1 | Dance Party   2 | Happy Hour  ... 

For this reason SETOF record is considered less practical. It should be used only when the column types of the results are not known in advance.

like image 131
Daniel Vérité Avatar answered Sep 20 '22 14:09

Daniel Vérité