In this article, you will learn about PostgreSQL for loop statements to iterate over a range of integers or a result set of a query.
The loop command is one of the plgpsql commands that helps us perform operations between given values.
The FOR LOOP command is one of the commands that allows us to make the operations in the Loop command easier by making them a little shorter.
General Usage is as follows
1 2 3 4 5 6 |
BEGIN FOR variable IN which values to operate between BY how many will it do LOOP Action to be taken END LOOP; END ; |
Let’s write a 10 by 10 for loop for the numbers between 100 and 200.
Insert into table
We will create a table with a single column called loop table and print the results returned from the loop in it.
1 2 3 4 5 6 7 8 9 10 11 |
create temp table looptable (id int) DO $$ BEGIN FOR sayi IN 100 .. 200 BY 10 LOOP insert into looptable values(sayi); --RAISE NOTICE 'Sayi : %', sayi; END LOOP; END$$; select *from looptable; |
We see that our For Loop loop runs and inserts records into 10 10 databases.