Simple Way to Get a Domain from an Email Using T-SQL

One of my recent projects required me to create a Microsoft SQL Server view that displayed (among other information) and email address and its underlying domain. Microsoft SQL Server and T-SQL provide a few simple functions that, when used together, make this a fairly easy task.

So here’s the T-SQL example (with the important stuff highlighted):

SELECT EMAIL,
RIGHT(EMAIL, LEN(EMAIL) - CHARINDEX('@', EMAIL)) AS 'DOMAIN' 
FROM MYTABLE

Parsing text inside a SQL Query can slow things down if you’re dealing with a large dataset, so use this code snippet with caution. If the application allows it, it’s generally a better idea to perform this kind of parsing in the application layer. ColdFusion, PHP and JavaScript provide comparable functions to T-SQL’s RIGHT, LEN and CHARINDEX.

If you’re feeling brave, you can also try pure RegEx rather than use native functions.

Leave a Reply