3

Postgresql 12. Want a function to return query by calling another function but don't know how to call.

create or replace function getFromA()
returns table(_id bigint, _name varchar) as $$
begin
    RETURN QUERY SELECT id, name from groups;
end; $$ language plpgsql;

create or replace function getFromB()
returns table(_id bigint, _name varchar) as $$
begin
    return query select getFromA();
end; $$ language plpgsql;

select getFromB();

gets error:

SQL Error [42804]: ERROR: structure of query does not match function result type
Detail: Returned type record does not match expected type bigint in column 1.
Where: PL/pgSQL function getfromb() line 3 at RETURN QUERY

How to fix this?

1 Answer 1

4

The problem is in getFromB():

return query select getFromA();

Unlike some other databases, Postgres allows set-returning functions directly in the select clause. This works, but can be tricky: this returns a set, hence not the expected structure.

You would need to select ... from getFromA() instead: this way it returns the proper data structure.

create or replace function getFromB()
returns table(_id bigint, _name varchar) as $$
begin
    return query select * from getFromA();
end; $$ language plpgsql;

Demo on DB Fiddle

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.