Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I would like to return a set of records from a pl/pgsql. Is there a way to do that without using the "for" construct and cursors? For instance when I compared these two stored procedures:

create or replace function sqlProc () returns setof integer as $$                                                                                                                                              
  select * from foo;
$$ language sql;

create or replace function plpgSqlProc () returns setof integer as $$
  c integer;
  for c in select * from foo loop
    return next c;
end loop;

$$ language plpgsql;

The pure SQL version has 2x better time performance than the pl/pgsql one! Unfortunately I have other logic that cannot be expressed in pure SQL so I am wondering how I should write my stored procedure?

share|improve this question
up vote 4 down vote accepted

There are a few ways of doing this in PostgreSQL depending on the versions you have to support. The simplest is:

create or replace function plpgSqlProc () returns setof integer as $$

RETURN QUERY select * from foo;

This being said, I find where you don't need helper procedural code, plain SQL functions are usually better. They are usually fast and sometimes they are even planner-transparent.

share|improve this answer
Thanks. But I see a lot of stored procedures that uses the for loop construct that only does return next inside the loop to iterate through query results. Is there any advantage to using that as opposed to using return query? – JRR Mar 3 '13 at 5:16
yes. Backward compatibility. RETURN QUERY is fairly new and early versions had significant corner case bugs. For new versions of PostgreSQL, those aren't issues. – Chris Travers Mar 3 '13 at 5:27

Your Answer


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.