Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create Array with range in PostgreSQL

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
like image 457
stderr Avatar asked Apr 09 '19 05:04

stderr


People also ask

How do I create an array in PostgreSQL?

Declaration of Array Types. To illustrate the use of array types, we create this table: CREATE TABLE sal_emp ( name text, pay_by_quarter integer[], schedule text[][] ); As shown, an array data type is named by appending square brackets ( [] ) to the data type name of the array elements.

What is [] in PostgreSQL?

We access array elements using the subscript within square brackets [] . By default, PostgreSQL uses one-based numbering for array elements. It means the first array element starts with number 1.

Can we store array in PostgreSQL?

Summary: PostgreSQL allows us to define a table column as an array type. The array must be of a valid data type such as integer, character, or user-defined types. To insert values into an array column, we use the ARRAY constructor.


1 Answers

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

like image 185
Tim Biegeleisen Avatar answered Nov 15 '22 06:11

Tim Biegeleisen