This is my (perhaps usual for you) non-optimized solution:
Workaround for PG problem with non-optimized internal function:
CREATE FUNCTION unnest_with_idx(anyarray)
RETURNS TABLE(idx integer, val anyelement) AS
$$
SELECT generate_series(1,array_upper($1,1)) as idx, unnest($1) as val;
$$ LANGUAGE SQL IMMUTABLE;
Test:
SELECT idx,val from unnest_with_idx(array[1,20,3,5]) as t;
But, as I said, non-optimized. I can't believe (!!) that PostgreSQL doesn't have an internal index for arrays ... ? But in this case, the question is how to directly access this index, where the GIN-like internal counter?
NOTE1: the solution above and the question is not the same as "how do you create an index by each element of an array?". Also not the same as "Can PostgreSQL index array columns?" because the function is for an isolated array, not for a table index for array fields.
NOTE2 (edited after answers): "array indexes" (more popular term) or "array subscripts" or "array counter" are terms that we can use in a semantic path to refer the "internal counter", the accumulator to the next array item. I see that no PostgreSQL command offer a direct access to this counter. As generate_series()
function, the generate_subscripts()
function is a sequence generator, and the performance is (best but) near the same. By other hand row_number()
function offers a direct access to a "internal counter of rows", but it is about rows, not about arrays, and unfortunately the performance is worse.