PestyLeader
PestyLeader

Reputation: 5

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?

Upvotes: 0

Views: 294

Answers (1)

user330315
user330315

Reputation:

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)

Upvotes: 1

Related Questions