EDUCBA Logo

EDUCBA

MENUMENU
  • Explore
    • EDUCBA Pro
    • PRO Bundles
    • Featured Skills
    • New & Trending
    • Fresh Entries
    • Finance
    • Data Science
    • Programming and Dev
    • Excel
    • Marketing
    • HR
    • PDP
    • VFX and Design
    • Project Management
    • Exam Prep
    • All Courses
  • Blog
  • Enterprise
  • Free Courses
  • Log in
  • Sign Up
Home Data Science Data Science Tutorials PostgreSQL Tutorial PostgreSQL For Loop
 

PostgreSQL For Loop

Payal Udhani
Article byPayal Udhani
EDUCBA
Reviewed byRavi Rathore

Updated May 10, 2023

PostgreSQL For Loop

 

 

Introduction to PostgreSQL For Loop

In the PostgreSQL database, we can use many conditional and looping statements. In this article, we will learn what is looping, why it is required, and the various types of looping statements, and how we can use for loop in PostgreSQL functions to achieve our intention or get our work done.

Watch our Demo Courses and Videos

Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more.

What Is Looping?

We often face a situation where we have to perform a specific activity multiple times in a repetitive fashion. In programming, looping through statements is a common technique in the technical world. Whenever we want to perform a certain task repetitively, we can loop through those statements that we want to perform repetitively. You can use a loop to execute statements for a specific number of times or until your requirement is fulfilled.

Types of Loops

In PostgreSQL, we have various types of looping facilities. We can stop looping with a plain loop with the EXIT WHEN statement. Another type of looping statement is the loop, and the last one is the while loop. To understand the examples, you need to have basic knowledge of PostgreSQL functions and CRUD operation statements like SELECT, UPDATE, INSERT and DELETE. Other than this, you should be aware of the arrays in PostgreSQL.

Syntax :

FOR [counting variable name] IN [REVERSE] [START VALUE] .. [END VALUE] [BY step value]
LOOP
[code/statements to repeat];
END LOOP;

Explanation:

For loop contains a counting variable that is unnecessary to declare outside the loop. You can declare it in the for loop statement itself. This counting variable has a START VALUE and an END VALUE as its range for which it will iterate. The step value is the stepping amount that specifies how much value is to be skipped from the start value till the end value while iterating. And the LOOP keyword marks the beginning of the for loop’s body that will be executed each time the loop is iterated.

You include the statements that you want to execute on a repetitive basis in the [code/statements to repeat] section, and the END LOOP marks the end of the for loop’s operation.REVERSE is the optional parameter in which, when specified, the counting variable will be decremented while iterating instead of incrementing each time the iteration is done. The for loop can be placed inside a certain function’s body, and this function can be called whenever we have to execute the for loop defined by us. It is necessary to define the range such that the looping should come to a halt and not iterate infinitely. Doing so will result in a wastage of CPU memory and execution and sometimes may crash the system.

Examples to Implement in PostgreSQL For Loop

Below are some examples of PostgreSQL For Loop:

Example #1

Let us first consider a simple example of printing the table of a particular integer that we pass to our function. Let us begin to be creating our function.

Code:

CREATE OR REPLACE FUNCTION displayTable(int) RETURNS void AS $$
DECLARE
tableOf int:=$1;
BEGIN
FOR counter IN 1..10
LOOP
RAISE NOTICE '%', tableOf*counter;
END LOOP;
END;
$$ LANGUAGE plpgsql;

So, after copying and pasting the above function in your psql command prompt, a function named displayTable will be created if CREATE FUNCTION is displayed at the end.

Output:

PostgreSQL For Loop Example 1

Now, to print the table, we will have to call the function displayTable() in the following way:

select displayTable(5);

Output:

PostgreSQL For Loop Example 1

Hence for printing the table of 5, the 5 number is multiplied by 1,2 and so on till 10, and a notice is displayed to print the table on the console. The for loop iterates 10 times to print any table.

Example #2

Reverse Order Looping: In this, we will see where our counter will decrement in value whenever it iterates in the for loop instead of incrementing. This functionality can be brought simply by specifying REVERSE after a counter variable is declared in for statement. Let’s consider an example where the function prints numbers in decreasing order from the number passed to it until 1.

Code:

CREATE OR REPLACE FUNCTION reverseExample(int) RETURNS void AS $$
DECLARE
passedValue int:=$1;
BEGIN
FOR sampleCounter IN REVERSE passedValue..1
LOOP
RAISE NOTICE 'My Current Value is = %', sampleCounter;
END LOOP;
END;
$$ LANGUAGE plpgsql;

After running the above function, it will give the following:

Output:

Reverse Order Example 2

Now, to print the values, we will have to write the select statement in the following way –

select reverseExample(12);

Output:

Reverse Order Example 2

Example #3

Step value other than 1: Suppose we have to print all the even numbers from 11 to 30. Then it is quite obvious that the first even number is 12, and after every 1 number, an even number comes. Hence if we increment by 2, then even numbers will print. Let us write a function for the same.

Code:

CREATE OR REPLACE FUNCTION displayEvenNumbers(int,int) RETURNS void AS $$
DECLARE
first int;
last int:=$2;
BEGIN
IF $1%2=0
THEN first=$1;
ELSE first=$1+1;
END IF;
FOR sampleCounter IN first..last BY 2
LOOP
RAISE NOTICE 'Even numbers : %', sampleCounter;
END LOOP;
END;
$$ LANGUAGE plpgsql;

Output:

PostgreSQL For Loop Example 3

For getting even numbers, we will query the following statement.

select displayevennumbers(11,30);

Output:

PostgreSQL For Loop Example 3

Example #4

Iterating an array using foreach.

Code:

CREATE FUNCTION displayRowValues(int[]) RETURNS void AS $$
DECLARE
sampleArray int[];
BEGIN
FOREACH sampleArray SLICE 1 IN ARRAY $1
LOOP
RAISE NOTICE 'The Row Value is = %', sampleArray;
END LOOP;
END;
$$ LANGUAGE plpgsql;

Copy and paste the above code in your PostgreSQL /psql command prompt to create a function named displayRowValues that will return the value and print the notice for each row of the array passed the function while calling it.

PostgreSQL For Loop Example 4

If you successfully create the function, PostgreSQL will display the CREATE FUNCTION statement after you copy and paste the above function definition and execute it. Now for calling the displayRowValues(), we will have to pass a parameter which should be an array. We will pass an array that will have the following values –

Array[[1,2],[3,4],[5,6],[7,8],[9,10],[11,12]];

which in graphical form is as follows –

1 2

3 4

5 6

7 8

9 10

11 12

Now, our calling statement will be

SELECT displayRowValues(Array[[1,2],[3,4],[5,6],[7,8],[9,10],[11,12]]);

The RAISE NOTICE ‘The Row Value is = %’, sampleArray; statement will execute for each row of the array that we have passed, and the notice for each row will be printed. Hence, the output of the above query statement will be as follows.

Output:

Sample Array Statement Example 4

Conclusion

You can use the for loop effectively and conveniently in PostgreSQL according to your necessity to loop around or execute certain statements repetitively. In PostgreSQL, you can iterate through the result set retrieved from a particular query using a for loop.

Recommended Articles

We hope that this EDUCBA information on “PostgreSQL For Loop” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

  1. How to Notify Works in PostgreSQL?
  2. PostgreSQL JSON (Examples)
  3. Introduction to PostgreSQL Timestamp
  4. PostgreSQL Primary Key

Primary Sidebar

Footer

Follow us!
  • EDUCBA FacebookEDUCBA TwitterEDUCBA LinkedINEDUCBA Instagram
  • EDUCBA YoutubeEDUCBA CourseraEDUCBA Udemy
APPS
EDUCBA Android AppEDUCBA iOS App
Blog
  • Blog
  • Free Tutorials
  • About us
  • Contact us
  • Log in
Courses
  • Enterprise Solutions
  • Free Courses
  • Explore Programs
  • All Courses
  • All in One Bundles
  • Sign up
Email
  • [email protected]

ISO 10004:2018 & ISO 9001:2015 Certified

© 2025 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

EDUCBA Login

Forgot Password?

🚀 Limited Time Offer! - ENROLL NOW