How can I pick only the non matching elements between two arrays.
Example:
base_array [12,3,5,7,8]
temp_array [3,7,8]
So here I wan
I would create a function using the same except logic as described by @a_horse_with_no_name:
CREATE FUNCTION array_subtract(a1 int[], a2 int[]) RETURNS int[] AS $$
DECLARE
ret int[];
BEGIN
IF a1 is null OR a2 is null THEN
return a1;
END IF;
SELECT array_agg(e) INTO ret
FROM (
SELECT unnest(a1)
EXCEPT
SELECT unnest(a2)
) AS dt(e);
RETURN ret;
END;
$$ language plpgsql;
Then you can use this function to change your base_array variable accordingly:
base_array := array_subtract(base_array, temp_array);
Using the @Denis's faster solution, and only SQL, we can express a generic function as
CREATE FUNCTION array_subtract(anyarray,anyarray) RETURNS anyarray AS $f$
SELECT array(
SELECT unnest($1)
EXCEPT
SELECT unnest($2)
)
$f$ language SQL IMMUTABLE;