I'm wondering how to pop a value off from the top of an Array in postgresql using plpgsql?
CREATE FUNCTION pop_off(arr ANYARRAY) RETURNING ANYARRAY AS $$
BEGIN
-- return array with first element removed
END;
$$ LANGUAGE plpgsql;
I'm wondering how to pop a value off from the top of an Array in postgresql using plpgsql?
CREATE FUNCTION pop_off(arr ANYARRAY) RETURNING ANYARRAY AS $$
BEGIN
-- return array with first element removed
END;
$$ LANGUAGE plpgsql;
Well, this wasn't as tough as I thought. Let's leverage the array_length method...
CREATE OR REPLACE FUNCTION pop_off(arr ANYARRAY) RETURNS ANYARRAY AS $$
BEGIN
RETURN (SELECT arr[2:array_length(arr,1)]);
END;
$$ LANGUAGE plpgsql;
There we go! Now let's test it...
LOG: statement: CREATE OR REPLACE FUNCTION pop_off(arr ANYARRAY) RETURNS ANYARRAY AS $$
BEGIN
RETURN (SELECT arr[2:array_length(arr,1)]);
END;
$$ LANGUAGE plpgsql;
CREATE FUNCTION
test_database=# SELECT pop_off('{1,2,3}'::int[]);
LOG: statement: SELECT pop_off('{1,2,3}'::int[]);
pop_off
---------
{2,3}
(1 row)