Search code examples
pythonsqlpostgresqlsql-insertasyncpg

Inserting multiple same values in PostgreSQL?


I've searched around and couldn't find a solution for my question - I want to insert multiple of the same values in a table?

For example, I'm using Asyncpg for python, I would do something like this:

for i in range(5):
  await execute("INSERT INTO table (column_a, column_b) VALUES (1, 2)")

while using a sequence to create unique "ID's" for each row. I understand you can use multiple values, but I want to make it so it's an arbitrary amount, how would I go about doing this?


Solution

  • In Postgres, you can insert 5 rows at once with a single query using generate_series():

    insert into mytable (column_a, column_b) 
    select 1, 2
    from generate_series(1, 5);