array indexes in postgres
Lets say I have an array of fruit types (Apple, Pear, Banana, Tangerine) and I want to turn each element in the array into a row I can do this.
select unnest(fruits)
from (select Array['Apple', 'Pear', 'Tangerine', 'Banana'] fruits) as list;
which returns:
unnest
-----------
Apple
Pear
Tangerine
Banana
(4 rows)
But it would be nice to have an array index as column in case the order of the elements in this array had some meaning. Postgres has a function generate_subscripts
to help you with array index elements.
select generate_subscripts(fruits, 1), unnest(fruits) from (select Array['Apple', 'Pear', 'Tangerine', 'Banana'] fruits) as list;
which returns:
generate_subscripts | unnest
---------------------+-----------
1 | Apple
2 | Pear
3 | Tangerine
4 | Banana
Throw a minus 1 in there if you want to be base zero :).
Tweet