Show Only the Domain of an Email Address in SQL Server

sqldba.blogMore of my SQL Server writing is at sqldba.blog, including the current take on SQL Server scripts: the DBA Scripts hub.

To show only the domain of an email address in SQL Server, find the @ with CHARINDEX and return everything after it. The short RIGHT and LEN version below works on clean data. On real data, trailing spaces and values with no @ break it, so further down there is a safer version I tested on SQL Server 2025.

Extracting email domains is useful for analysing trends, spotting invalid emails, or finding the most frequent domains in your dataset. The examples use a small sample table you can create on any test instance.

Step 1: Setting Up Test Data

To get started, run the following script to create a sample database and populate it with test email data:

SQL
USE master;
GO
DROP DATABASE IF EXISTS fatanta;
CREATE DATABASE fatanta;
GO
USE fatanta;
GO
DROP TABLE IF EXISTS players;
CREATE TABLE players (
  id INT IDENTITY PRIMARY KEY NOT NULL,
  first_name VARCHAR(100),
  surname VARCHAR(100),
  user_role VARCHAR(40),
  email_address VARCHAR(200)
);
INSERT INTO players VALUES
('peter','whyte','master','pete_test_mail@hotmail.com'),
('john','mcdonald','admin','johnman64@gmail.com'),
('alex','thompson','member','stickman22@hotmail.co.uk'),
('fiona','thompson','member','stickmanswife@hotmail.co.uk'),
('mo','molsen','member','mo3@outlook.com'),
('desire','nicholson','member','nicholsons.desire@outlook.com'),
('don','donaldson','member','thedon@outlook.com');

Step 2: Extracting Email Domains

Query 1: Show Distinct Email Domains
To extract unique email domains from the table, use this query:

SQL
-- Show distinct email domains
SELECT DISTINCT
	RIGHT(email_address, LEN(email_address) - CHARINDEX('@', email_address)) AS [email_domain]
FROM players
ORDER BY 1;
sql to show distinct email providers

CHARINDEX returns the position of the @, and RIGHT takes the characters after it: the length of the address minus that position. On the sample data this returns four domains: gmail.com, hotmail.co.uk, hotmail.com and outlook.com.

Query 2: Count Email Domains
If you want to count the occurrences of each domain, use this query:

SQL
-- Show distinct email domains with counts
SELECT
	RIGHT(email_address, LEN(email_address) - CHARINDEX('@', email_address)) AS [email_domain],
	COUNT(*) AS [count]
FROM players
GROUP BY RIGHT(email_address, LEN(email_address) - CHARINDEX('@', email_address))
ORDER BY [count] DESC;
sql to count email domains

Sorting by [count] DESC puts the most frequent domains first. Domains with the same count come back in no particular order, so add the domain as a second sort column if you need the output to be repeatable.

Where the RIGHT and LEN Version Goes Wrong

Email columns are rarely as tidy as a sample table. I ran the same expression against a few awkward values on my SQL Server 2025 lab instance, with brackets added round the output so the spaces show:

Code
label            input                      RIGHT/LEN result
---------------  -------------------------  ------------------
no @             [not-an-email]             [not-an-email]
NULL             NULL                       NULL
two @            [odd@name@example.com]     [name@example.com]
trailing spaces  [sam@gmail.com   ]         [il.com   ]
leading space    [ sam@gmail.com]           [gmail.com]
upper case       [Sam@GMAIL.com]            [GMAIL.com]
  • Trailing spaces cut the domain short. LEN ignores trailing spaces but RIGHT counts them, so gmail.com came back as il.com with the spaces still on the end.
  • No @ returns the whole value. CHARINDEX returns 0, so the expression hands back the full string, and it lands in your domain counts as if it were a domain.
  • More than one @ splits at the first one. That is rarely valid, but it is worth knowing which side you are on.
  • Case is kept. On a case-insensitive collation the GROUP BY still puts GMAIL.com and gmail.com together, but the label shown is whichever one SQL Server meets first.

A common variation takes the text after the last @ with REVERSE. That one fails outright on a value with no @, because the length passed to RIGHT becomes -1: Invalid length parameter passed to the RIGHT function. (Msg 536). One bad row stops the whole query.

A Safer Way to Get the Domain

SUBSTRING from the position after the @ avoids the length arithmetic altogether. Add TRIM for stray spaces, LOWER so the labels are consistent, and a WHERE clause to leave out values that are not email addresses:

SQL
-- Distinct email domains, tolerant of spaces, case and missing @
SELECT DISTINCT
	LOWER(TRIM(SUBSTRING(email_address, CHARINDEX('@', email_address) + 1, 200))) AS email_domain
FROM players
WHERE CHARINDEX('@', email_address) > 0
ORDER BY email_domain;

-- Domain counts
SELECT d.email_domain, COUNT(*) AS domain_count
FROM players AS p
CROSS APPLY (SELECT LOWER(TRIM(SUBSTRING(p.email_address, CHARINDEX('@', p.email_address) + 1, 200))) AS email_domain) AS d
WHERE CHARINDEX('@', p.email_address) > 0
GROUP BY d.email_domain
ORDER BY domain_count DESC, d.email_domain;

The 200 matches the column size, and SUBSTRING stops at the end of the string anyway. The CROSS APPLY names the expression once, so it is not repeated in the GROUP BY. TRIM arrived in SQL Server 2017; on older versions use LTRIM(RTRIM(...)) instead.

I tested it on the sample data plus three messier rows: Sam@GMAIL.com with trailing spaces, not-an-email and a NULL. The count query returned:

Code
email_domain   domain_count
-------------  ------------
outlook.com    3
gmail.com      2
hotmail.co.uk  2
hotmail.com    1

The upper-case Gmail address with trailing spaces is counted with the other Gmail row, and the two rows that are not email addresses are left out instead of showing up as domains.

Find the Rows With No Domain

The rows the WHERE clause skips are often the more interesting result, because they are the bad data:

SQL
-- Values that are not email addresses
SELECT id, email_address
FROM players
WHERE email_address IS NULL
   OR CHARINDEX('@', email_address) = 0;

On my test data that returned the not-an-email row and the NULL one.

If You Group by Domain Often

If domain reports are a regular job on a big table, store the domain as a persisted computed column and index it, so the string work is done once when a row is written rather than on every query:

SQL
ALTER TABLE players ADD email_domain AS
	LOWER(TRIM(SUBSTRING(email_address, NULLIF(CHARINDEX('@', email_address), 0) + 1, 200))) PERSISTED;

CREATE INDEX ix_players_email_domain ON players (email_domain);

The NULLIF turns a missing @ into NULL, so those rows have a NULL domain instead of the whole value. Indexing a computed column needs QUOTED_IDENTIFIER on. SSMS has it on by default, but sqlcmd does not: my first run from sqlcmd failed with Msg 1934 until I added the -I switch.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *