Recently, I was working on a requirement that required me to execute a for loop in PostgreSQL. In this article, I will walk you through the solution to fix the error upper bound of for loop cannot be null.
Upper Bound of for Loop cannot be Null
I executed the below query.
do $$
begin
for count in 1..null loop
raise notice 'count:%',count;
end loop;
end;
$$
After executing the above query, I encountered the error shown below.

Reason for this error
In PostgreSQL, there are two bounds for a loop: a lower bound and an upper bound. The lower bound starts from lower values, which means the loop will begin at [0, 1,…]. The upper bound is the highest value of the loop, at which the iteration will terminate.
Remember that the upper bound can’t be null in PostgreSQL. If it is provided as null, the message box will display a logic error. Since I kept the upper bound as null so I got this error.
Solution
To fix this error, I kept an upper limit of four instead of null as mentioned in the query below.
do $$
begin
for count in 1..4 loop
raise notice 'count:%',count;
end loop;
end;
$$
After executing the above query, I got the expected output without any issue as shown in the screenshot below.

Video Tutorial
You may also like the following articles.

Kumar Saurabh is a freelance software engineer who builds web and mobile apps with Next.js, React, Flutter and Python. From 2021 to 2024, Saurabh worked as an IT analyst and developer at TSInfo Technologies, writing technical articles on SQL and PostgreSQL. Saurabh writes the PostgreSQL, MySQL, MariaDB and MongoDB tutorials on DatabaseFAQs.com and holds a Master of Computer Applications (MCA) from Chandigarh University.