EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login

PostgreSQL For Loop

Home » Data Science » Data Science Tutorials » PostgreSQL Tutorial » PostgreSQL For Loop

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.

What Is Looping?

We often face a situation where we have to perform a specific activity multiple times in a repetitive fashion. This is programming, and the technical world is called looping through the statements. Whenever we want to perform a certain task repetitively, we can loop through those statements that we want to perform repetitively. We can loop the statements for a specific number of times or until and unless our requirement is fulfilled.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Types of Loops

In PostgreSQL, we have various types of looping facilities. We can use a plain loop with the EXIT WHEN statement to stop looping. 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 which is not necessary to declare outside the for a loop. It can be declared in the for loop statement itself. This counting variable has 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 will be iterated.

The statements that we want to execute on a repetitive basis are included in the [code/statements to repeat] section, and END LOOP marks the ending of the for loop working. REVERSE is the optional parameter 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 wastage of CPU memory and execution and sometimes may crash the system.

Popular Course in this category
PostgreSQL Course (2 Courses, 1 Project)2 Online Courses | 1 Hands-on Project | 7+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (2,974 ratings)
Course Price

View Course

Related Courses

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 will iterate 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 us see an example where the numbers will print in the decreasing order from the number which is passed to function 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: Now, 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 and 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 the function is created successfully, then the CREATE FUNCTION will be displayed after you copy and paste and fire the above function definition. 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

The for loop can be used effectively and conveniently as per our necessity to loop around or execute certain statements repetitively. Besides this, even the result set retrieved from a particular query can be iterated using for loop in PostgreSQL.

Recommended Articles

This is a guide to PostgreSQL For Loop. Here we discuss the Introduction to PostgreSQL For Loop and the practical examples and different subquery expressions. You can also go through our suggested articles to learn more –

  1. How to Notify Works in PostgreSQL?
  2. PostgreSQL JSON (Examples)
  3. Introduction to PostgreSQL Timestamp
  4. PostgreSQL Primary Key
  5. Guide to PostgreSQL Tablespaces
  6. PostgreSQL List Tables
  7. Guide to PostgreSQL IF Statement

PostgreSQL Course (2 Courses, 1 Project)

2 Online Courses

1 Hands-on Project

7+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
PostgreSQL Tutorial
  • Control Statement
    • PostgreSQL IF Statement
    • PostgreSQL if else
    • PostgreSQL CASE Statement
    • PostgreSQL LOOP
    • PostgreSQL For Loop
    • PostgreSQL While Loop
  • Basic
    • What is PostgreSQL
    • PostgreSQL Features
    • How to Install PostgreSQL
    • PostgreSQL Versions
    • PostgreSQL Architecture
    • PostgreSQL GUI
    • PostgreSQL Variables
    • PostgreSQL Data Types
    • PostgreSQL NOT NULL
    • PostgreSQL Integer
    • PostgreSQL Boolean
    • PostgreSQL NULLIF
    • PostgreSQL Administration
    • PostgreSQL Commands
    • PostgreSQL Operators
    • PostgreSQL IN Operator
  • Joins
    • Joins in PostgreSQL
    • PostgreSQL Inner Join
    • PostgreSQL Outer Join
    • LEFT OUTER JOIN in PostgreSQL
    • PostgreSQL FULL OUTER JOIN
    • PostgreSQL LEFT JOIN
    • PostgreSQL Full Join
    • PostgreSQL Cross Join
    • PostgreSQL NATURAL JOIN
    • PostgreSQL UPDATE JOIN
  • Queries
    • PostgreSQL Queries
    • PostgreSQL WHERE Clause
    • PostgreSQL WITH Clause
    • PostgreSQL ORDER BY
    • PostgreSQL ORDER BY Random
    • PostgreSQL GROUP BY
    • PostgreSQL group_concat
    • PostgreSQL HAVING
    • PostgreSQL Recursive Query
  • Advanced
    • PostgreSQL Schema
    • Postgres List Schemas
    • PostgreSQL VARCHAR
    • Array in PostgreSQL
    • PostgreSQL DDL
    • PostgreSQL List Users
    • Postgres Default User
    • Postgres add user
    • PostgreSQL log_statement
    • PostgreSQL String Functions
    • PostgreSQL Compare Strings
    • PostgreSQL Text Search
    • PostgreSQL TEXT
    • PostgreSQL String Array
    • PostgreSQL Constraints
    • PostgreSQL UNIQUE Constraint
    • PostgreSQL INTERSECT
    • PostgreSQL Like
    • Cursors in PostgreSQL
    • PostgreSQL UNION ALL
    • Indexes in PostgreSQL
    • PostgreSQL Index Types
    • PostgreSQL REINDEX
    • PostgreSQL UNIQUE Index
    • PostgreSQL Clustered Index
    • PostgreSQL DROP INDEX
    • PostgreSQL DISTINCT
    • PostgreSQL FETCH
    • PostgreSQL RAISE EXCEPTION
    • PostgreSQL Auto Increment
    • Sequence in PostgreSQL
    • Wildcards in PostgreSQL
    • PostgreSQL Subquery
    • PostgreSQL Alias
    • PostgreSQL LIMIT
    • PostgreSQL Limit Offset
    • PostgreSQL LAG()
    • PostgreSQL Table
    • Postgres Show Tables
    • PostgreSQL Describe Table
    • PostgreSQL Lock Table
    • PostgreSQL ALTER TABLE
    • Postgres Rename Table
    • Postgres DROP Table
    • PostgreSQL Functions
    • PostgreSQL Math Functions
    • PostgreSQL Window Functions
    • Aggregate Functions in PostgreSQL
    • PostgreSQL Primary Key
    • Foreign Key in PostgreSQL
    • PostgreSQL Procedures
    • PostgreSQL Stored Procedures
    • PostgreSQL Views
    • PostgreSQL Materialized Views
    • Postgres Create View
    • PostgreSQL Triggers
    • PostgreSQL DROP TRIGGER
    • PostgreSQL Date Functions
    • PostgreSQL TO_DATE()
    • PostgreSQL Timestamp
    • PostgreSQL CURRENT_TIMESTAMP()
    • PostgreSQL Notify
    • PostgreSQL RANK()
    • PostgreSQL Select
    • PostgreSQL Average
    • PostgreSQL DATE_PART()
    • PostgreSQL EXECUTE
    • PostgreSQL COALESCE
    • PostgreSQL EXTRACT()
    • PostgreSQL Sort
    • PostgreSQL TO_CHAR
    • PostgreSQL Interval
    • PostgreSQL Number Types
    • PostgreSQL ROW_NUMBER
    • Alter Column in PostgreSQL
    • PostgreSQL Identity Column
    • PostgreSQL SPLIT_PART()
    • PostgreSQL CONCAT()
    • PostgreSQL replace
    • PostgreSQL TRIM()
    • PostgreSQL MAX
    • PostgreSQL DELETE
    • PostgreSQL Float
    • PostgreSQL OID
    • PostgreSQL log
    • PostgreSQL REGEXP_MATCHES()
    • PostgreSQL MD5 
    • PostgreSQL NOW()
    • PostgreSQL RANDOM
    • PostgreSQL round
    • PostgreSQL Trunc()
    • PostgreSQL TIME
    • PostgreSQL IS NULL
    • PostgreSQL CURRENT_TIME
    • PostgreSQL MOD()
    • Postgresql Count
    • PostgreSQL Datetime
    • PostgreSQL MIN()
    • PostgreSQL age()
    • PostgreSQL enum
    • PostgreSQL OR
    • PostgreSQL Wal
    • PostgreSQL NOT IN
    • PostgreSQL SET
    • PostgreSQL Current Date
    • PostgreSQL Compare Date
    • PostgreSQL SERIAL
    • PostgreSQL Database
    • PostgreSQL Clone Database
    • PostgreSQL Copy Database
    • PostgreSQL Restore Database
    • PostgreSQL DROP DATABASE
    • PostgreSQL ALTER DATABASE
    • Postgres DROP Database
    • Postgres Dump Database
    • PostgreSQL OFFSET
    • PostgreSQL GRANT
    • PostgreSQL COMMIT
    • PostgreSQL ROLLUP
    • PostgreSQL JSON
    • EXPLAIN ANALYZE in PostgreSQL
    • PostgreSQL Temporary Table
    • PostgreSQL cluster
    • PostgreSQL Replication
    • PostgreSQL Logical Replication
    • PostgreSQL flush privileges
    • PostgreSQL Tablespaces
    • CAST in PostgreSQL
    • PostgreSQL CTE
    • hstore in PostgreSQL
    • PostgreSQL DECODE()
    • PostgreSQL Vacuum
    • PostgreSQL EXCLUDE
    • Postgres Change Password
    • Postgres Delete Cascade
    • PostgreSQL EXCEPT
    • PostgreSQL Roles
    • PostgreSQL Link
    • PostgreSQL Partition
    • PostgreSQL column does not exist
    • PostgreSQL Log Queries
    • PostgreSQL escape single quote
    • PostgreSQL Query Optimization
    • PostgreSQL Character Varying
    • PostgreSQL Transaction
    • PostgreSQL Extensions
    • PostgreSQL Import CSV
    • PostgreSQL Client
    • PostgreSQL caching
    • PostgreSQL JDBC Driver
    • PostgreSQL Interview Questions
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

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

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

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

Forgot Password?

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

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

Special Offer - PostgreSQL Course (2 Courses, 1 Project) Learn More