Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I select a subset of an array in Postgres?

Tags:

Assuming I have an array in one of my postgres columns:

> select array[1,2,3,4];
   array   
-----------
 {1,2,3,4} 

How do I select a subset of the items from that array, in general? For instance, if I want to select items from the x index to the y index, how would I grab the items in that range (x to y)?

I'm using PostgreSQL 9.4.

like image 465
jbranchaud Avatar asked Sep 26 '15 05:09

jbranchaud


People also ask

What is [] in PostgreSQL?

We access array elements using the subscript within square brackets [] . By default, PostgreSQL uses one-based numbering for array elements.

What is Unnest in PostgreSQL?

The purpose of unnest function in PostgreSQL is to expand the array into rows. Unnest function generates a table structure of an array in PostgreSQL. Unnest array function is beneficial in PostgreSQL for expanding the array into the set of values or converting the array into the structure of the rows.

Is it OK to use arrays in Postgres?

If you are sure you'll stick with Postgres, then you can safely use arrays where you find appropriate. They exist for a reason and are neither bad design nor non-compliant.

How do I find the length of an array in PostgreSQL?

PostgreSQL makes it less complicated for using arrays in a query and finding the length of a column using only the simple syntax array_length (column_name, int). The “array_length” in this syntax returns the length of an array of the first argument i.e., column_name, and “int” tells the dimension of the array measured.


1 Answers

From the fine manual:

8.15.3. Accessing Arrays
[...]
We can also access arbitrary rectangular slices of an array, or subarrays. An array slice is denoted by writing lower-bound:upper-bound for one or more array dimensions.
[...]
It is possible to omit the lower-bound and/or upper-bound of a slice specifier; the missing bound is replaced by the lower or upper limit of the array's subscripts.

For example:

=> select (array[1,2,3,4,5,6])[2:5];
   array   
-----------
 {2,3,4,5}
(1 row)

=> select (array[1,2,3,4,5,6])[:5];
    array    
-------------
 {1,2,3,4,5}
(1 row)

=> select (array[1,2,3,4,5,6])[2:];
    array    
-------------
 {2,3,4,5,6}
(1 row)

=> select (array[1,2,3,4,5,6])[:];
     array     
---------------
 {1,2,3,4,5,6}
(1 row)

So to get a slice from index x to y (inclusive), you'd say:

array_column[x:y]
like image 144
mu is too short Avatar answered Sep 23 '22 01:09

mu is too short