Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a SQL for loop to insert rows into database?

Tags:

sql

postgresql

I'm using Postgres, and I have a large number of rows that need to be inserted into the database, that differ only in terms of an integer that is incremented. Forgive what may be a silly question, but I'm not much of a database guru. Is it possible to directly enter a SQL query that will use a loop to programatically insert the rows?

Example in pseudo-code of what I'm trying to do:

for i in 1..10000000 LOOP   INSERT INTO articles VALUES(i) end loop; 
like image 554
William Jones Avatar asked Sep 21 '10 20:09

William Jones


People also ask

How can you insert rows in table in SQL?

If you want to add data to your SQL table, then you can use the INSERT statement. Here is the basic syntax for adding rows to your SQL table: INSERT INTO table_name (column1, column2, column3,etc) VALUES (value1, value2, value3, etc); The second line of code is where you will add the values for the rows.

How do I insert a row into a database?

To insert a row into a table, you need to specify three things: First, the table, which you want to insert a new row, in the INSERT INTO clause. Second, a comma-separated list of columns in the table surrounded by parentheses. Third, a comma-separated list of values surrounded by parentheses in the VALUES clause.


2 Answers

Hopefully I've understood what you need (tested on 8.2):

INSERT INTO articles (id, name) SELECT x.id, 'article #' || x.id   FROM generate_series(1,10000000) AS x(id); 
like image 148
Milen A. Radev Avatar answered Sep 30 '22 17:09

Milen A. Radev


In SQL Server you can do:

DECLARE @i int SET @i = 1  WHILE @i<1000000     BEGIN         INSERT INTO articles         VALUES @i         SET @i=@i+1     END 
like image 31
JNK Avatar answered Sep 30 '22 18:09

JNK