Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a function that needs to return results from more than 1 table. Is this possible to do so in Postgresql (9.1 now, planning migration to 9.2 soon)? If so, how.

For example

create or replace function f1()
returns ???
as $body$ begin
    return query select x.*
        from users x;
    return query select x.*
        from user_preferences x join users y using(user_id) ; -- more where clauses
    return query select x.*
        from user_permissions x join users y using(user_id) ; -- more clauses
end; $body$ language 'plpgsql';

The alternatives I considered were: (a) Doing a cartesian product of users and user_preferences (etc.) but that will lead to a gigantic result table and a truly convoluted code. (b) First doing a select on users and then iterating the list of users and depending on their attributes, doing additional iterations, but that will lead to way too many database calls. And, why shall I write code that SQL is so superbly good at?

Is there a clean cut way of getting multiple resultsets out of a pg function? I have searched the postgresql documentation but could not find any guidance.

Thanks a lot.

share|improve this question

1 Answer 1

Because Pg (at time of writing) doesn't support stored procedures, only functions callable from SQL, there's no provision for returning multiple result sets directly.

However, you can define a function as RETURNS SETOF refcursor. The function can create multiple temporary tables, open a cursor for each table and return the cursor.

This is a bit clumsy to work with, but is effective.

share|improve this answer
    
thanks. It looks like this should do, I will try it out. –  Dinesh Feb 21 '13 at 8:05

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.