Getting the last word from a Postgres string, declaratively

前端 未结 8 2390
无人及你
无人及你 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:27

    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)];
    

提交回复
热议问题