Getting the last word from a Postgres string, declaratively

前端 未结 8 2374
无人及你
无人及你 2021-02-07 00:18

[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

相关标签:
8条回答
  • 2021-02-07 00:44

    UPDATE: the question was edited, so I update my answer.

    You can also use array_upper() to return the element itself (not just its index):

    SELECT arr[array_upper(arr, 1)] FROM (SELECT ARRAY[1,2,3,6] AS arr) AS t
    

    So the anwer is:

    SELECT arr[array_upper(arr, 1)] FROM (SELECT string_to_array('one two three', ' ') AS arr) AS t
    

    result: 'three'

    0 讨论(0)
  • 2021-02-07 00:48

    You can do the following:

    SELECT (ARRAY[1,8,3,7])[array_upper(ARRAY[1,8,3,7], 1)];

    I.e. get the index and then select that last element.

    0 讨论(0)
提交回复
热议问题