Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to insert values into a postgres table using for loop?

I have a script like this in postgres

begin;

INSERT INTO "schema"."table"(price, different_table_foreign_key)
VALUES
    (1, 1)

end;

for testing purposes I want to fill table 100 times with the same values as seen above.

how can I do this using a for loop?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

No need for a loop, you can use generate_series() for that:

INSERT INTO "schema"."table"(price, different_table_foreign_key)
select 1,1
from generate_series(1,100);

If you want a different value for each row, just use the one returned by `generate_series()

INSERT INTO "schema"."table"(price, different_table_foreign_key)
select 1, g.value
from generate_series(1,100) as g(value)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading