Skip to content
Advertisement

How do I generate an array containing the numbers 1 to n in Postgres

I’m hoping there exists something like this:

> SELECT nrange(10)
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

Similar to the range function in languages like Python and Racket. Of course, if no such function exists in PostgreSQL I’d be more than satisfied to know the idiomatic way to approach this. Thanks!

This is a bit different from the question How can I generate a series of repeating numbers in PostgreSQL? in that I am not trying to generate a series of repeating numbers, but rather an array of sequential numbers.

Advertisement

Answer

In the event that you want an array, you can aggregate the values in to an array:

select array_agg(gs.val order by gs.val)
from generate_series(1, 10) gs(val);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement