I need to update column 'sp' (varchar) using column 'a_sp' (varchar) in the same table. Both columns hold from zero/null to multiple lists of values. These values are concatenated with the '+' sign and stored with this sign at the start and end of it. I want to take/loop through each value in 'a_sp' and check if it is already existing in its respective 'sp' cell. If it is, nothing is appended to 'sp' and if not the value is appended. I would appreciate your help as I am just adjusting to DB programming from OOP.

UPDATE work.table
SET sp =
CASE
WHEN (sp IS NULL OR sp = '') THEN a_sp --no sp val return a_sp
WHEN (sp IS NOT NULL OR sp != '') THEN --if there exists sp val
CASE
WHEN sp LIKE '%'||a_sp||'%' THEN sp --if existing sport val is similar to a_sp return sp
ELSE sp||ltrim(a_sp, '+') --if existing sp val not similar to asp, append
END
ELSE sp --if both cases above not met (which is odd) return sp
END
WHERE a_sp IS NOT NULL;
My Solution (Although tacky) -
--I found the function (below) which creates a distinct array of any array type at https://postgres.cz/wiki/Array_based_functions
CREATE OR REPLACE FUNCTION work.array_distinct(anyarray)
RETURNS anyarray AS $$
SELECT ARRAY(SELECT DISTINCT unnest($1))
$$ LANGUAGE sql;
--for sp col
UPDATE work.tab
SET sp =
CASE
WHEN (sp IS NULL OR sp = '') THEN a_sp --no sp val return a_sp
WHEN (sp IS NOT NULL OR sp != '') THEN
--below i did quite some manipulations
--i removed the '+' to the left of a_sp column
--then concatenated sp and asp columns
--i converted the concatenated result to array based on the string '+' as a divider
--next, i used the function 'array_distinct' above to return unique values # this was quite a way to avoid looping through the lists to append
--i converted the result above back to string with a string '+' separator
--i finally added string '+' to both ends of my result
replace(replace('+'||rtrim(array_to_string(array_distinct(regexp_split_to_array(replace(sp||ltrim(a_sp, '+'), '+', ' '), E'\\s+')::varchar[]), ','), ',')||'+',',', '+'), '++', '+') --if there exists sp val
--ELSE sport --if both cases above not met (which is odd) return sp
END
WHERE a_sp IS NOT NULL;