[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
Edited: THIS IS WRONG -- SEE BELOW FOR CORRECT ANSWER --
I guess you must use array_length()
:
SELECT string_to_array('hi guys, welcome', ' ') AS arr INTO temparr;
SELECT * FROM temparr;
arr
----------------------
{hi,"guys,",welcome}
SELECT arr[array_length(arr,1)] FROM temparr;
arr
---------
welcome
To use this declaratively, (on the fly) you can create a little SQL function:
CREATE FUNCTION last_elem (text[]) RETURNS text AS $$
SELECT $1[array_length($1,1)];
$$ LANGUAGE SQL;
select last_elem(string_to_array('hi guys, welcome', ' '));
last_elem
-----------
welcome
------- EDITED -- CORRECT ANSWER FOLLOWS ----------------------
The above is not correct because in Postgresql arrays can sometimes be not one-based.
The correct way, then, is with array_upper()
CREATE FUNCTION last_elem (text[]) RETURNS text AS $$
SELECT $1[array_upper($1,1)];
$$ LANGUAGE SQL;
select last_elem(string_to_array('hi guys, welcome', ' '));
last_elem
-----------
welcome