11

In PostgreSQL, it is possible to create an array with elements (https://www.postgresql.org/docs/current/functions-array.html):

SELECT ARRAY[1,2,3,4] AS indexes;

Is there a function to generate an array by specifying begin and end? like

SELECT array_from_to(1, 4) AS indexes

2 Answers 2

12

We can use a combination of the ARRAY function with generate_series, e.g.

SELECT ARRAY(
    SELECT a.n
    FROM generate_series(1, 4) AS a(n)
);

Demo

Sign up to request clarification or add additional context in comments.

1 Comment

Could be even shorter: ARRAY(SELECT * FROM generate_series(1, 4))
9

You can use the ARRAY_AGG function in conjunction with the GENERATE_SERIES function.

For example:

SELECT ARRAY_AGG(index) AS indexes
FROM GENERATE_SERIES(1,4) AS index;

Output:

  indexes  
-----------
 {1,2,3,4}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.