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.
I am Bijay having more than 15 years of experience in the Software Industry. During this time, I have worked on MariaDB and used it in a lot of projects. Most of our readers are from the United States, Canada, United Kingdom, Australia, New Zealand, etc.
Want to learn MariaDB? Check out all the articles and tutorials that I wrote on MariaDB. Also, I am a Microsoft MVP.