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
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 |
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.
In version 9.3 and above you can do:
update users set flags = array_remove(flags, 'active')
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
The simplest way to remove last value:
array1 = array[1,2,3]
array1 = ( select array1[1:array_upper(array1, 1) - 1] )
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
)
)