I have many records where 2 columns contain words which shall be uniquely concatenated. all words shall be distinct in the result.
The order of both text arrays shall be kept.

> 
> **Col1**: mr. spock *eats 13 fish*
> 
> 
> **Col2**: **he** *eats 13 fish*
> 
> 
> 

The idea is to concatenate only missing words.

> 
> result: mr. spock **he** *eats 13 fish*
> 
> 
> 

I've tried to create arrays of both text columns with PostgreSQL's function

`regexp_split_to_array`

This is, what solved my problem:

```
CREATE OR REPLACE FUNCTION merge_strings(str1 text[], str2 text[])
  RETURNS text[]
  LANGUAGE plpgsql
AS
$body$
DECLARE
    res TEXT[];
    t1 TEXT;
    t2 TEXT;
    pos2 int := 1;
    pos3 int;
begin
    FOREACH t1 in array str1 LOOP
        pos3 := array_position(str2, t1, pos2);
        while (pos2 <= pos3) LOOP
        --iterate over words in second text-array until first found word from first text-array 
            t2 := str2[pos2];
            if (t2 != t1) then
                --only use words that are not equal         
                res := array_append(res, t2);
            end if;
            pos2 := pos2 + 1;
        END LOOP;
        res := array_append(res, t1);
    END LOOP;
    FOREACH t2 in array str2 LOOP
    --add all missing words from second text-array
        pos3 := array_position(res, t2);
        if (pos3 is null) then
            res := array_append(res, t2);
        end if;
    end loop;
    return res;
END;
$body$

```