Find All Unique Email Domains Problem
#3059
Description
LeetCode Problem 3059.
Table: Emails
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| id | int |
| email | varchar |
+-------------+---------+
id is the primary key (column with unique values) for this table.
Each row of this table contains an email. The emails will not contain uppercase letters.
Write a solution to find all unique email domains and count the number of individuals associated with each domain. Consider only those domains that end with .com.
Return the result table orderd by email domains in ascending order.
The result format is in the following example.
Example 1:
Input:
Emails table:
+-----+-----------------------+
| id | email |
+-----+-----------------------+
| 336 | [email protected] |
| 489 | [email protected] |
| 449 | [email protected] |
| 95 | [email protected] |
| 320 | [email protected] |
| 411 | [email protected] |
+----+------------------------+
Output:
+--------------+-------+
| email_domain | count |
+--------------+-------+
| outlook.com | 2 |
| yahoo.com | 1 |
+--------------+-------+
Explanation:
- The valid domains ending with ".com" are only "outlook.com" and "yahoo.com", with respective counts of 2 and 1.
Output table is ordered by email_domains in ascending order.
Solution
Approach: Cut the domain after the @
Keep the emails ending in .com, take everything after the last @ with SUBSTRING_INDEX(email, '@', -1), and count rows per domain. The .com filter is on the whole address, which is the same as filtering the domain because the domain is the tail of the address. Order by the domain.
SELECT SUBSTRING_INDEX(email, '@', -1) AS email_domain,
COUNT(*) AS count
FROM Emails
WHERE email LIKE '%.com'
GROUP BY email_domain
ORDER BY email_domain;