[EDIT] original title of this question was \"Getting the last element of a Postgres array, declaratively\"
How to obtain the last element of the array in Postgr
This is a more generic answer to 'how to get the last element of an array'.
trader=# create table temp (name varchar);
CREATE TABLE
trader=# insert into temp (name) values ('foo bar baz');
INSERT 0 1
trader=# select (regexp_split_to_array(name, ' ')) from temp;
regexp_split_to_array
-----------------------
{foo,bar,baz}
(1 row)
trader=# select (regexp_split_to_array(name, ' '))[array_upper(regexp_split_to_array(name, ' '), 1)] from temp;
regexp_split_to_array
-----------------------
baz
(1 row)
Returns the index of the last element of an array. So to use it, you have to reference the array twice: some_array[array_upper(some_array, 1)]
So if you already have your array:
trader=# create view temp2 as (select regexp_split_to_array(name, ' ') as name_parts from temp);
CREATE VIEW
trader=# select * from temp2;
name_parts
---------------
{foo,bar,baz}
(1 row)
It's less verbose to select the last element:
trader=# select name_parts[array_upper(name_parts, 1)] from temp2;
name_parts
------------
baz
(1 row)