Thread: Find difference between two Text fields

Find difference between two Text fields

From
Peter Hunsberger
Date:
Can anyone give me a way to find the difference between two text
fields on a character by character basis.  Essentially,  I'd like to
logically AND the two together and for any position that has a
non-zero result show whatever character is in that position for the
second string.  The solution can be postgres specific but something
approaching ANSI SQL would also be helpful (if possible).

--
Peter Hunsberger

Re: Find difference between two Text fields

From
Aleksander Kmetec
Date:
Hi,

there might be a better solution out there, but it seemed like an interesting problem so I wrote this function:

CREATE OR REPLACE FUNCTION stringdiff(text, text)
RETURNS TEXT
AS $$
     SELECT array_to_string(ARRAY(
         SELECT
             CASE WHEN substring($1 FROM n FOR 1) = substring($2 FROM n FOR 1)
                  THEN ' '
                  ELSE substring($2 FROM n FOR 1)
             END
         FROM generate_series(1, character_length($1)) as n), '');
$$ language sql;


Use it like this:
SELECT stringdiff('aaaaaaaaaa', 'axaaacaaza');

  stringdiff
------------
   x   c  z

Regards,
Aleksander


Peter Hunsberger wrote:
> Can anyone give me a way to find the difference between two text
> fields on a character by character basis.  Essentially,  I'd like to
> logically AND the two together and for any position that has a
> non-zero result show whatever character is in that position for the
> second string.  The solution can be postgres specific but something
> approaching ANSI SQL would also be helpful (if possible).
>