Remove array values in pgSQL

后端 未结 10 2246
不知归路
不知归路 2021-02-06 22:10

Is there a way to remove a value from an array in pgSQL? Or to be more precise, to pop the last value? Judging by this list the answer seems to be no. I can get the result I wan

相关标签:
10条回答
  • 2021-02-06 22:29

    There IS a SIMPLE way to remove a value from an array in PLAIN SQL:

    SELECT unnest('{5,NULL,6}'::INT[]) EXCEPT SELECT NULL
    

    it will remove all NULL values from array. Result will be:

    #| integer |
    ------------
    1|    5    |
    2|    6    |
    
    0 讨论(0)
  • 2021-02-06 22:31

    I'm running on 9.2 and I'm able to execute this:

    update tablename set arrcolumn=arrcolumn[1:array_length(arrcolumn)-1];
    

    or you can shift off the front element with the same kind of thing:

    update tablename set arrcolumn=arrcolumn[2:array_length(arrcolumn)];
    

    Careful, programmers -- for some reason still unknown to science, pgsql arrays are 1-indexed instead of 0-indexed.

    0 讨论(0)
  • 2021-02-06 22:35

    In version 9.3 and above you can do:

    update users set flags = array_remove(flags, 'active')
    
    0 讨论(0)
  • 2021-02-06 22:38

    I've created a array_pop function so you can remove an element with known value from an array.

    CREATE OR REPLACE FUNCTION array_pop(a anyarray, element character varying)
    RETURNS anyarray
    LANGUAGE plpgsql
    AS $function$
    DECLARE 
        result a%TYPE;
    BEGIN
    SELECT ARRAY(
        SELECT b.e FROM (SELECT unnest(a)) AS b(e) WHERE b.e <> element) INTO result;
    RETURN result;
    END;
    $function$ 
    

    there is also a gist version https://gist.github.com/1392734

    0 讨论(0)
  • 2021-02-06 22:41

    The simplest way to remove last value:

    array1 = array[1,2,3]
    array1 = ( select array1[1:array_upper(array1, 1) - 1] )
    
    0 讨论(0)
  • 2021-02-06 22:42

    No, I don't think you can. At least not without writing something ugly like:

    SELECT ARRAY (
     SELECT UNNEST(yourarray) LIMIT (
      SELECT array_upper(yourarray, 1) - 1
     )
    )
    
    0 讨论(0)
提交回复
热议问题