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.
We access array elements using the subscript within square brackets [] . By default, PostgreSQL uses one-based numbering for array elements.
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.
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.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With