Skip to content
Advertisement

how to get slice of an array in AWS Athena?

I have an array of unknown length in AWS Athena. I want to get all elements expect for the first one and concatenate into a string.

I can do with a known length, but I don’t see how for unknown length. In this example:

select this_arr, second, array_join(myslice, ' ') as myslice_joined
from
(select this_arr, element_at(this_arr, 2) as second, slice(this_arr, 2, 4) as myslice
from 
(select array ['one','two','three', 'four'] as this_arr));

enter image description here

What I want is myslice_joined. I could use slice because I knew it had four elements, but what if it’s more? Slice does not take a -1 as the last element, as you can do elsewhere.

Advertisement

Answer

You can use cardinality to determine the array length:

select this_arr,
    second,
    array_join(myslice, ' ') as myslice_joined
from (
        select this_arr,
            element_at(this_arr, 2) as second,
            slice(this_arr, 2, cardinality(this_arr)) as myslice
        from (
                select array [ 'one', 'two', 'three', 'four' ] as this_arr
            )
    );

Output:

this_arr second myslice_joined
[one, two, three, four] two two three four
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement