Remove array values in pgSQL

后端 未结 10 2417
不知归路
不知归路 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: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

提交回复
热议问题