In a basic Postgres function tutorial there is an example with OUT
parameters like so:
create or replace function hi_lo(a numeric,
b numeric,
c numeric,
OUT hi numeric,
OUT lo numeric)
as $$
begin
hi := greatest(a, b, c);
lo := least(a, b, c);
end; $$
language plpgsql;
Then results look like
select hi_lo(2, 3, 4);
-- returns one column, "hi_lo" with value "(4, 2)".
select * from hi_lo(2, 3, 4);
-- returns two columns, "hi" / 4 and "lo" / 2.
But suppose you want to execute the function on columns that come from performing a join, and that you do not have access to modify the function or use an alternative function? For example, using some toy data:
select hi_lo(a.actor_id, length(a.name), ma.movie_id)
from
actors a
join
movies_actors ma
on
a.actor_id = ma.movie_id
limit 10;
returns results in a single column "hi_lo" have 2-tuple values.
Wrapping the query in parentheses and trying to a select *
from it does not change the format of the output. So
select *
from (
select hi_lo(a.actor_id, length(a.name), ma.movie_id)
from
actors a
join
movies_actors ma
on
a.actor_id = ma.movie_id
limit 10;
) rr
does not impact the result shape.
The following try results in the error "subquery must return only one column"
select (
select * from hi_lo(a.actor_id, length(a.name), ma.movie_id)
)
from
actors a
join
movies_actors ma
on
a.actor_id = ma.movie_id
limit 10;
Finally, I also tried unnest
but it gives an argument type error as the tuple values are not treated as arrays.
How can you achieve multiple columns in the output when you cannot move the function evaluation into the from
section?
See Question&Answers more detail:
os