0

I'm an absolute noob and couldn't find the answer to this one.
How can I add the result into a temporary table?
Perhaps you guys have some tips for me to improve my code as well?

I created a function here with cursors through the results. But I need to:

drop function if exists non_married_presidents();
create or replace function non_married_presidents()
returns varchar as $$
declare
    c_emp cursor for
        select name, birth_year from president
        where id not in(select pres_id from pres_marriage);
begin


    for emp in c_emp loop
        raise notice 'name: %, birth_year: %', emp.name, emp.birth_year;
    end loop;
end;
$$language plpgsql;

Call:

select non_married_presidents();
Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
Sjoerd Brauer
  • 129
  • 1
  • 12

1 Answers1

0

You ask:

How can I add the result into a temporary table?

You may be overthinking this. Just use CREATE TEMP TABLE AS ...

CREATE TEMP TABLE tmp_tbl AS
-- INSERT INTO tmp_tbl (name, birth_year) -- or insert into existing table
SELECT name, birth_year FROM president p
WHERE  NOT EXISTS (SELECT 1 FROM pres_marriage WHERE pres_id = p.id);

You don't need a cursor. It's a rare occasion that an explicit cursor would be the best option in plpgsql.

While being at it, NOT IN is a construct best avoided:

Community
  • 1
  • 1
Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228