Getting the last word from a Postgres string, declaratively
Use array_upper():
SELECT array_upper(ARRAY[1,2,5,6], 1);
If I understand your question correctly you have a string and you're first splitting it on some separator and then afterwards finding the last element of the array and discarding the rest.
You could miss out the middle man and get the last element directly:
SELECT regexp_replace('foo bar baz', '^.* ', '')
Result:
baz
Q: what I want to do is to sort by the last word of a specific column
When dealing with an actual array of text
(not a string), use array_upper()
in the index.
Demo for 1-dimensional array
WITH x(a) AS (
VALUES
('{zoo, zar, zaz}'::text[])
,('{3,4,5,6}')
,('{foo, bar, baz}')
)
SELECT *
FROM x
ORDER BY a[array_upper(a, 1)];
Demo for 2-dimensional array
WITH x(a) AS (
VALUES
('{{zoo, zar, zaz}
,{4,5,6}
,{14,15,16}
,{foo, bar, zzzaz}}'::text[])
,('{{zoo, zar, baz}
,{4,5,6}
,{14,15,16}
,{foo, bar, aaaaz}}'::text[])
)
SELECT *
FROM x
ORDER BY a[array_upper(a, 1)][array_upper(a, 2)];