Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Databases
  • SQL
  • MySQL
  • PostgreSQL
  • PL/SQL
  • MongoDB
  • SQL Cheat Sheet
  • SQL Interview Questions
  • MySQL Interview Questions
  • PL/SQL Interview Questions
  • Learn SQL and Database
Open In App
Next Article:
PostgreSQL - While Loops
Next article icon

PostgreSQL – For Loops

Last Updated : 10 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In PostgreSQL, PL/pgSQL (Procedural Language/PostgreSQL) introduces control structures like FOR loops to simple complex data processing. The FOR loop allows developers to iterate over a specified range of integers or the results of a query and making repetitive tasks more manageable.

This feature is crucial for performing calculations, data manipulation and reporting efficiently. In this article, we will learn various FOR loop examples in PL/pgSQL by focusing on iterating over integers and explain their practical applications.

PostgreSQL For Loops

  • In PostgreSQL, FOR loops are used to iterate over a range of integers, a result set or the result set of a dynamic query.
  • This allows developers to execute a set of statements multiple times and make it easier to handle repetitive tasks or to process data in batches.

Types of FOR Loops in PostgreSQL

1. FOR Loop to Iterate Over a Range of Integers

This type of loop allows you to specify a range of integers and execute a block of code for each integer in that range. The REVERSE option allows iteration in reverse order. The BY clause specifies the increment step, defaulting to 1.

[ <<label>> ]
for loop_cnt in [ reverse ] from.. to [ by step ] loop
statements
end loop [ label ];

Explanation:

  • An integer variable loop_cnt is created at first, which is accessible inside the loop only. After each iteration, the for loop adds the step to the loop_cnt. However, when we use the reverse option, the for loop subtracts the step from loop_cnt after each iteration.
  • To specify the lower and upper bound of the range, we use the from and to expressions. Before entering the loop, the for loop evaluates these expressions.
  • The step that follows the by keyword specifies the iteration step with 1 as the default value. This step expression is evaluated only once.

The following flowchart describes the for loop statement:

Flowchart of For loop

Example 1: Iterate from 1 to 10

The following code uses the for loop statement to iterate over ten numbers from 1 to 10 and display each of them in each iteration:

DO $$
BEGIN
FOR cnt IN 1..10 LOOP
RAISE NOTICE 'cnt: %', cnt;
END LOOP;
END; $$

Output:

Example 2: Iterate from 10 to 1

The following code uses the for loop statement to iterate over ten numbers from 10 to 1 and display each of them in each iteration:

DO $$
BEGIN
FOR cnt IN REVERSE 10..1 LOOP
RAISE NOTICE 'cnt: %', cnt;
END LOOP;
END; $$

Output:

2. FOR Loop to Iterate Over a Result Set

The syntax of the for loop statement to iterate over a result set of a query:

[ <<label>> ]
FOR target IN query LOOP
statements
END LOOP [ label ];

First, we create a sample table using the below commands to perform examples:

CREATE TABLE employees (
employee_id serial PRIMARY KEY,
full_name VARCHAR NOT NULL,
manager_id INT
);

Then we insert data into our employee table as follows:

INSERT INTO employees (
employee_id,
full_name,
manager_id
)
VALUES
(1, 'M.S Dhoni', NULL),
(2, 'Sachin Tendulkar', 1),
(3, 'R. Sharma', 1),
(4, 'S. Raina', 1),
(5, 'B. Kumar', 1),
(6, 'Y. Singh', 2),
(7, 'Virender Sehwag ', 2),
(8, 'Ajinkya Rahane', 2),
(9, 'Shikhar Dhawan', 2),
(10, 'Mohammed Shami', 3),
(11, 'Shreyas Iyer', 3),
(12, 'Mayank Agarwal', 3),
(13, 'K. L. Rahul', 3),
(14, 'Hardik Pandya', 4),
(15, 'Dinesh Karthik', 4),
(16, 'Jasprit Bumrah', 7),
(17, 'Kuldeep Yadav', 7),
(18, 'Yuzvendra Chahal', 8),
(19, 'Rishabh Pant', 8),
(20, 'Sanju Samson', 8);

The table is:

Example 1: Iterate Over Employee IDs

The following code uses the for loop statement to iterate over largest 10 employee id:

DO $$
DECLARE
f RECORD;
BEGIN
FOR f IN SELECT employee_id, full_name
FROM employees
ORDER BY employee_id DESC
LIMIT 10
LOOP
RAISE NOTICE '% - %', f.employee_id, f.full_name;
END LOOP;
END;
$$;

Output:
 

3. FOR Loop to Iterate Over the Result Set of a Dynamic Query

The syntax of the for loop statement to iterate over a result set of a dynamic query:

[ <<label>> ]
FOR row IN EXECUTE query_expression [ USING query_param [, ...] ] LOOP
statements
END LOOP [ label ];

Explanation:

  • query_expression is an SQL statement.
  • The USING clause is used to pass the query parameters.

Example 1: Dynamic Query with Sorting

The following code shows how to use the for loop statement to loop through a dynamic query. It has the following two configuration variables:

  • sort_type: 1 to sort by employee id, 2 to sort by length of name
  • rec_count: is the number of records to query from the table.
DO $$
DECLARE
sort_type SMALLINT := 1; -- 1: employee_id, 2: length of name
rec_count INT := 10; -- number of records to query
rec RECORD;
query TEXT;
BEGIN
query := 'SELECT full_name, employee_id FROM employees ';

IF sort_type = 1 THEN
query := query || 'ORDER BY employee_id DESC ';
ELSIF sort_type = 2 THEN
query := query || 'ORDER BY LENGTH(full_name) DESC ';
ELSE
RAISE 'Invalid sort type %s', sort_type;
END IF;

query := query || ' LIMIT $1';

FOR rec IN EXECUTE query USING rec_count LOOP
RAISE NOTICE '% - %', rec.employee_id, rec.full_name;
END LOOP;
END;
$$;

Output:

If we change the sort_type to 2, we’ll get the following output:

sort_type

Conclusion

Overall, using the FOR loop in PostgreSQL enhances the capabilities of PL/pgSQL, allowing for efficient data manipulation and processing. Understanding the loop syntax is essential for implementing effective control structures within your database functions. Additionally, integrating dynamic SQL queries in PostgreSQL with loop statements empowers developers to create flexible and adaptable code that can respond to varying data requirements. Mastering the PostgreSQL loop statement not only improves productivity but also ensures that database operations are executed seamlessly and effectively.



Next Article
PostgreSQL - While Loops

K

kishankr11710428
Improve
Article Tags :
  • Databases
  • PostgreSQL
  • Technical Scripter
  • postgreSQL-basics
  • Technical Scripter 2020

Similar Reads

  • PostgreSQL - While Loops
    When working with PostgreSQL, knowing how to efficiently use loops can be essential for running iterative operations. PostgreSQL’s WHILE loop allows developers to repeatedly execute a block of code as long as a specified condition remains true. PostgreSQL provides the loop statement which simply def
    4 min read
  • PL/SQL For Loop
    PL/SQL stands for Procedural Language/ Structured Query Language. It has block structure programming features. With PL/SQL, you can fetch data from the table, add data to the table, make decisions, perform repetitive tasks, and handle errors.PL/SQL supports SQL queries. To fetch records, process dat
    4 min read
  • PostgreSQL - Alias
    PostgreSQL aliases are powerful tools that allow you to assign temporary names to tables or columns within your queries. These aliases only exist during the execution of the query, making your SQL code more readable and efficient. What is a PostgreSQL Alias?An alias in PostgreSQL is a temporary name
    2 min read
  • PostgreSQL - Cursor
    In the area of database management, effective data retrieval is essential particularly when handling large datasets. PostgreSQL offers the functionality of a cursor which allows for incremental data retrieval from extensive result sets. By using PostgreSQL cursor syntax, developers can manage memory
    5 min read
  • PostgreSQL - CASE
    In PostgreSQL, the CASE expression allows you to perform conditional operations within your SQL queries. It evaluates a list of conditions and returns a result when the first condition is met. If no conditions are met, it returns the result specified in the ELSE clause. Let us better understand the
    3 min read
  • PostgreSQL - Loop Statement
    The LOOP statement in PL/pgSQL is used to create an unconditional loop that executes a block of code repeatedly until a RETURN or EXIT statement terminates it. This article will help you understand the syntax and usage of the LOOP statement, and provide examples to display its application. Let us ge
    3 min read
  • PostgreSQL - GRANT
    In PostgreSQL, the GRANT statement is a powerful tool used to assign privileges to a role, allowing it to alter database objects like tables, views, functions, and more. Here we will learn about the syntax and application of the GRANT statement, with examples to illustrate its usage in PostgreSQL. S
    3 min read
  • PostgreSQL - IN operator
    The IN operator in PostgreSQL is a powerful and efficient tool used to filter records based on a predefined set of values. When used with the WHERE clause, it simplifies SQL queries and enhances readability, making it a key component of SQL query optimization for data retrieval and database manipula
    4 min read
  • PostgreSQL - INSERT
    PostgreSQL INSERT statement is one of the fundamental SQL commands used to add new rows to a specified table within a PostgreSQL database. This command allows users to insert data efficiently, whether for a single record or multiple records at once. With the PostgreSQL INSERT INTO clause, we can spe
    5 min read
  • PostgreSQL Exercises
    PostgreSQL is a powerful, open-source relational database system that supports complex queries, data types, and performance optimization features. This article provides PostgreSQL practice exercises with solutions, allowing learners to explore how joins, aggregations, triggers, and foreign keys work
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences