The PostgreSQL Documentation on arrays provides an example using [-1] to access what appears to be the last element of an array; however while SELECT arr[2:3]; produces {5,9}, arr[2:-1] results in {}.
How can the last element of an array be obtained in PostgreSQL?
Edit: Windows, PostgreSQL v9.2.1
I think you’re misinterpreting the example. PostgreSQL arrays don’t have to be indexed from 1 to
n, that’s just the default:The example you’re looking at is this:
But those negative numbers aren’t indexing from the end of the arrays as in languages such as Perl. In the
FROM (SELECT ...part, they’re specifying the starting and ending indexes so the -1 inf1[1][-1][5]is just a plain old index. Consider thisarray_dimsresult:If you’re using the default 1-based arrays then you can get the last element with a simple
arr[array_length(arr, 1)]. If you’re not using the default[1:n]arrays then you’ll have to mess around witharray_lowerandarray_upperto get the first and last elements; or, depending on the circumstances, you might be able to useunnestto unpack the array then work with the array as a rowset.