Upper Bound of for Loop cannot be Null

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.

Upper Bound of for Loop cannot be Null

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.

Upper Bound of for Loop cannot be Null.

Video Tutorial

You may also like the following articles.

Top 200 SQL Server Interview Questions and Answers

Free PDF On Top 200 SQL Server Interview Questions And Answers

Download A 40 pages PDF And Learn Now.