Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get email domain name from email ID in T-SQL assuming there is more than one delimited value?

I have an email ID column and would like to extract the domain only accounting for sub domains if applicable. My current query is assuming the first delimited value only

For instance ‘abc@gmail.com’ = gmail

However, if the email is like ‘abc@gmail.co.com’ it will be extracted as gmail.co – I want it to be gmail only as well

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My query:

SUBSTRING(col_email, 
    CHARINDEX('@', col_email) + 1, 
    LEN(col_email) - CHARINDEX('@', col_email) - CHARINDEX('.', REVERSE(col_email))) as domain

>Solution :

You can use a few of CHARINDEXs and SUBSTRING for this. This assumes that all email addresses are valid (so have a . after the @) and that you don’t have any outlier email addresses like Steve"@"home.has_a_valid_address@mydomain.com:

SELECT SUBSTRING(Email, CHARINDEX('@',Email)+1,CHARINDEX('.',Email,CHARINDEX('@',Email)) - CHARINDEX('@',Email) -1) AS YourDomain
FROM (VALUES('abc@gmail.com'))V(Email)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading