How to Fix “ERROR: step size cannot equal zero” While Creating a Series in PostgreSQL

In PostgreSQL, the generate_series() is a popularly used function that creates a series of integers/dates within the determined range. However, Postgres users occasionally face a “step size can’t equal zero” error while generating a series. The stated error arises because of specifying a wrong step size, i.e., 0. To rectify this error a couple of solutions are used in Postgres.

This blog post will provide several fixes for the “step size can’t equal zero” error in PostgreSQL.

How to Fix “ERROR: step size cannot equal zero” While Creating a Series in PostgreSQL?

In Postgres, the generate_series() function is used to create a sequence of numbers/dates. The stated function accepts an optional parameter named step size that can be any number other than 0. If a user passes a step size equal to zero, then the generate_series() function will throw the following error:

img

To rectify this error, the below-listed solutions can be used in Postgres:

  • Utilize the Default Step Size.
  • Specify a Non-zero Step Size.

Solution 1: Utilize the Default Step Size

The most suitable approach to fix the “step size can’t equal zero” error is, don’t specify any step size at all. So that the generate_series() function utilizes the default step size. Here is how the generate_series() function works with the default step size:

SELECT * FROM generate_series(5, 15);

From the below-provided snippet, you can notice that the stated problem has been rectified. The series has been successfully generated within the specified range:

img

Solution 2: Specify a Non-zero Step Size

An alternative solution to the stated problem is specifying a non-zero step size. Upon doing so, the “step size cannot equal zero” error will be resolved, as shown in the following example:

SELECT * FROM generate_series(5, 15, 3);

In this example code, the step size is specified as “3”. The following will be the output for the given generate_series() function:

img

That’s all you need to learn about the “step size can’t equal zero” error in Postgres.

Conclusion

The "step size can't equal zero" error in PostgreSQL occurs when a user uses a wrong step size of 0 while generating a series using the generate_series() function. To rectify the stated error, either use the default step size or specify a non-zero step size. The best possible fix to the stated error is don’t specify any step size at all. In that case, the generate_series() function will utilize the default step size. This write-up has provided a couple of solutions to fix the “step size can’t equal zero” error in PostgreSQL.