Aleš
Aleš

Reputation: 79

SQL, replace part of a string with email

In my DB I have a column user_email with values:

[email protected]
[email protected]
[email protected]

I would only like to change part of email address that comes after @, so that the resulting column would have values:

[email protected]
[email protected]
[email protected]

How could I achieve that?

Upvotes: 1

Views: 599

Answers (5)

Barbaros Özhan
Barbaros Özhan

Reputation: 65363

You might use replace, substr and instr together as :

SELECT replace( '[email protected]',
         substr('[email protected]',instr('[email protected]','@'),length('[email protected]'))
                              ,'@other.net') as result_str;

 result_str
-------------
[email protected]

or from your table(tab) with a column called as email :

select replace(email,substr(email,instr(email,'@'),length(email)),'@other.net') result_str
  from tab;

result_str
-------------
[email protected]
[email protected]
[email protected]

Rextester Demo

Upvotes: 0

Strawberry
Strawberry

Reputation: 33945

select concat
        (substring
          ('[email protected]',1,char_length
            ('[email protected]')-
            char_length
              (substring_index
                ('[email protected]','.',-1))),'net') x;

| x            |
| ------------ |
| [email protected] |

View on DB Fiddle

Upvotes: 0

Aleš
Aleš

Reputation: 79

I've found following solution that seems to do the trick:

UPDATE table_name SET user_email = REPLACE(user_email, '@test.com', '@other.net');

Upvotes: 1

Zaynul Abadin Tuhin
Zaynul Abadin Tuhin

Reputation: 31991

use SUBSTRING_INDEX and concat fnction

select concat(SUBSTRING_INDEX("[email protected]", "@", 1),'@other.net')

output [email protected]

so for your column user_email it would be

select concat(SUBSTRING_INDEX(user_email, "@", 1),'@other.net')

Upvotes: 0

Fahmi
Fahmi

Reputation: 37473

use replace function

demo

select replace(name,substring(name,position('@' in name),length(name)-position('@' in name)+1),'@other.net')

select replace('[email protected]',substring('[email protected]',position('@' in '[email protected]'),
length('[email protected]')-position('@' in '[email protected]')+1),'@other.net')

output:

val             n
[email protected]    [email protected]

Upvotes: 0

Related Questions