Skip to content
Advertisement

Store select query as variable and loop for entire variable

I want to store the result of select query from another table and set it as variable. Then i want to loop through the variable and use it in my loop for. The question is how i can store the result of select query from my table?

do $$
declare
 ids <data_type> := <SELECT DISTINCT (*) from a>;
begin 
for id in ids loop
insert
 into
 b (
 select from c where c.id in id
end loop;
end $$

Advertisement

Answer

Why not run a single query?

insert into b ( . . . )
    select . . .
    from c
    where c.id in (select id from a);

The . . . are for listing the columns/expressions for the insert.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement