I’ve the following two columns in Postgres table
name | last_name
----------------
AA | AA aa
BBB | BBB bbbb
.... | .....
.... | .....
How can I update the last_name by removing name text from it?
final out put should be like
name | last_name
----------------
AA | aa
BBB | bbbb
.... | .....
.... | .....
This only removes one copy from the beginning of the column and correctly removes the trailing space.
Edit
I’m using a regular expression here.
'^' || name || ' 'builds the regular expression, so with the ‘Davis McDavis’ example, it builds the regular expression'^Davis '. The^causes the regular expression to be anchored to the beginning of the string, so it’s going to match the word ‘Davis’ followed by a space only at the beginning of the string it is replacing in, which is thelast_namecolumn.You could achieve the same effect without regular expressions like this:
You need to add two to the length to create the offset because substr is one-based (+1) and you want to include the space (+1). However, I prefer the regular expression solution even though it probably performs worse because I find it somewhat more self-documenting. It has the additional advantage that it is idempotent: if you run it again on the database it won’t have any effect. The
substr/offsetmethod is not idempotent; if you run it again, it will eat more characters off your last name.