0

I need to clean up an address field in PostgreSQL 8.4 by removing everything to the right of a street name. This includes dropping suites ("100 Broadway Street Suite 100") and correcting names that have unit numbers appended to the street name ("100 Broadway Street100") so that the result in both cases would be "100 Broadway Street".

Essentially I am trying to remove everything to the right of "Street". I can't seem to get a replace function to work without individually coding for each case. A rtrim function also doesn't work because the characters I want removed would be a wildcard.

Here is what I am trying to get to work:

update *tablename* set *fieldname* = replace (*fieldname*, '%STREET%', '%STREET')

This SQL below works, but I don't want to code each possible combination:

UPDATE *tablename* set *fieldname* = replace (*fieldname*, ' SUITE 100', '');
UPDATE *tablename* set *fieldname* = replace (*fieldname*, ' STREET100', ' STREET');

How can I remove everything to the right of a string "Street" without explicitly specifying what follows "Street"?

Thanks for the help.

2 Answers 2

1

Try something like this:

SELECT regexp_replace('100 broadway street 100', '(.*)(Street).*', '\1\2', 'i');

The above is basically looking for anything followed by "Street" (case insensitively, per the last 'i' agrument), and then stripping off everything after the "Street", which I think is what you're asking for. See http://www.postgresql.org/docs/current/static/functions-matching.html for more details.

Sign up to request clarification or add additional context in comments.

Comments

0

This truncates after the first instance of 'STREET':

UPDATE tablename
  SET fieldname = SUBSTR(fieldname, 1, position('STREET' IN fieldname) + 5)
  WHERE fieldname LIKE '%STREET%'

Update: If the desire is to have a case-insensitive search of "STREET":

UPDATE tablename
  SET fieldname = SUBSTR(fieldname, 1, position('STREET' IN UPPER(fieldname)) + 5)
  WHERE UPPER(fieldname) LIKE '%STREET%'

2 Comments

Note, although OP's examples use "STREET" (all-caps), he said in his original description 'I am trying to remove everything to the right of "Street"', so I'm assuming he really wants a case-insensitive search for "Street".
Thanks for the reply. I already updated the field to be all upper case, but both snippets are useful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.