0

I have a table like below...

value Name
Data-1 Aarong
Data-125 Aarong
INT-121 Aarong
INT-122 Aarong

I would like to update value column with existing value. After update value column like below.

value Name
D-1 Aarong
D-125 Aarong
I-121 Aarong
I-122 Aarong
1
  • 1
    What if you have BLA-126 or FOO-789? Do you always want the first letter from the part before the dash? Commented Dec 24, 2020 at 8:49

3 Answers 3

3

For this particular case, the simplest way is to execute two queries.

update table set data=replace(data,'Data-','D-') where position('Data-' in data) > 0;

and

update table set data=replace(data,'INT-','I-') where position('INT-' in data) > 0;   
Sign up to request clarification or add additional context in comments.

Comments

2

If the string always contain just one dash, you could do this with split_part():

update mytable set value = 
    left(value, 1) || '-' || split_part(value, '-', 2)

if there may be more than one dash, and you want everything after the first:

update mytable set value = 
    left(value, 1) || substr(value, position('-' in value))

Demo on DB Fiddle

Comments

1

You can use regexp_replace(). To see the new values:

select regexp_replace(value, '^(.).*(-.*)$', '\1\2')
from t;

You can interpret this as:

  • ^ from the beginning of the string
  • (.) take the first character and remember it.
  • .* ignore any number of characters (until the following patter)
  • (-.*) remember the hyphen and what follows
  • $ to the end of the string

The '\1\2' is the replacement, which is the first character and then the hyphen and everything afterwards.

To change them:

update t
    set value = regexp_replace(value, '^(.).*(-.*)$', '\1\2');

Regular expressions are quite powerful. If you need to tweak the pattern matching rules, it is usually much simpler to adjust a regular expression than to deal with more cumbersome string operations.

Here is a db<>fiddle.

Comments

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.