Re: Find difference between two Text fields - Mailing list pgsql-general

From Aleksander Kmetec
Subject Re: Find difference between two Text fields
Date
Msg-id 4A6A75A5.4070203@intera.si
Whole thread Raw
In response to Find difference between two Text fields  (Peter Hunsberger <peter.hunsberger@gmail.com>)
List pgsql-general
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).
>

pgsql-general by date:

Previous
From: "Brian A. Seklecki"
Date:
Subject: Re: Disable databse listing for non-superuser (\l) ?
Next
From: Jan-Erik
Date:
Subject: Re: split string by special characters