Getting the last element of a Postgres array, declaratively

Posted by Wojciech Kaczmarek on Stack Overflow See other posts from Stack Overflow or by Wojciech Kaczmarek
Published on 2010-06-01T12:57:16Z Indexed on 2010/06/01 13:03 UTC
Read the original article Hit count: 186

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?

© Stack Overflow or respective owner

Related posts about sql

Related posts about arrays