Getting the last word from a Postgres string, declaratively

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

    Edited: THIS IS WRONG -- SEE BELOW FOR CORRECT ANSWER --

    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
    

    ------- EDITED -- CORRECT ANSWER FOLLOWS ----------------------

    The above is not correct because in Postgresql arrays can sometimes be not one-based.

    The correct way, then, is with array_upper()

    CREATE FUNCTION last_elem (text[]) RETURNS text AS $$
     SELECT $1[array_upper($1,1)];
    $$ LANGUAGE SQL;
    
    
     select last_elem(string_to_array('hi guys, welcome', ' '));
     last_elem
    -----------
     welcome
    

提交回复
热议问题