UPDATE table SET last_name = regexp_replace(last_name, '^' || name || ' ', '');
This removes only one copy from the beginning of the column and correctly deletes the trailing space.
Edit
I use regex here. '^' || name || ' '
'^' || name || ' '
creates a regular expression, so with the example "Davis McDavis", he builds the regular expression '^Davis '
. ^
causes the regular expression to snap to the beginning of the line, so it will match the word "Davis", followed by a space only at the beginning of the line into which it is replaced, in which the last_name
column is located.
You can achieve the same effect without regular expressions like this:
UPDATE table SET last_name = substr(last_name, length(name) + 2);
You need to add two lengths to create the offset, because substr is unidirectional (+1), and you want to include a space (+1). However, I prefer the regex solution, although it's probably worse because I find it somewhat more self-documenting. It has the added benefit of being idempotent: if you run it again in the database, it will have no effect. The substr/offset
method is not idempotent; if you run it again, it will contain more characters from your last name.
source share