views:

148

answers:

2

How to obtain the last element of the array in Postgres?

I need to do it declaratively as I want to use it as a ORDER BY criteria. I wouldn't want to create a special PGSQL function for it, the less changes to the database the better in this case.

In fact, what I want to do is to sort by the last word of a specific column containing multiple words. Changing the model is not an option here.

In other words, I want to push Ruby's sort_by {|x| x.split[-1]} into the database level. I can split a value into array of words with Postgres string_to_array or regexp_split_to_array functions, then how to get its last element?

+2  A: 

Use array_upper():

SELECT array_upper(ARRAY[1,2,5,6], 1);
Frank Heikens
Your answer is 100% correct, but the example could be confusing since both the index and the value of the max array index is 4 (since PostgreSQL arrays start from 1). Changing the "4" in your example to pretty much any other number makes *what* is being returned more clear.
Matthew Wood
You're right! Changed it, the result is 4, the upper key of the array.
Frank Heikens
Well it returns the index of the last element, not the element itself. So still no way to use it declaratively without creating temporary table/array/function.
Wojciech Kaczmarek
For the record, this answer is incorrect. See mine below
leonbloy
+1  A: 

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
leonbloy