Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Query to Count Unique Domains from Email Address field

I'd like to get a better idea of what domains my customers are using. I could easily do this in PHP by explodeing each address and counting the domain that way. But I'm wondering if there's a way to get this information with just a plain MySQL query?

This is what sample output would look like:

gmail.com | 3942

yahoo.com | 3852

hotmail.com | 209

... and so on, where the first column is the email addresses domain, and the 2nd column is the number of addresses at that domain.

like image 807
Ian Avatar asked Mar 13 '10 23:03

Ian


3 Answers

You would have to do something like this:

SELECT substring_index(email, '@', -1) domain, COUNT(*) email_count
FROM table
GROUP BY substring_index(email, '@', -1)

-- If you want to sort as well:
ORDER BY email_count DESC, domain;
like image 156
Wolph Avatar answered Nov 20 '22 11:11

Wolph


Adding ORDER BY to WoLpH's answer makes the output more clear:

SELECT substring_index(email, '@', -1), COUNT(*) AS MyCount
FROM `database`.`table`
GROUP BY substring_index(email, '@', -1)
ORDER BY MyCount DESC;
like image 40
Brad Avatar answered Nov 20 '22 11:11

Brad


Small tweak to Wolph's original above to shorten a bit and add nice column name and limit results in case list is long. Adjust limit to your own liking

select substring_index(email, '@', -1) AS domain, count(*) from TABLE group by domain order by count(*) DESC limit 40;
like image 1
Marc Avatar answered Nov 20 '22 11:11

Marc