Description:
Three Gmail users, but the query only counts 2.
Why does Gmail only count 2?
SELECT SPLIT_PART(
email, '@', 2) AS domain,
COUNT(*) AS users
FROM users
WHERE email IS NOT NULL
GROUP BY SPLIT_PART(
email, '@', 2)
ORDER BY users DESC;
The fix:
SELECT SPLIT_PART(LOWER(TRIM(email)), '@',2) AS domain, COUNT(*) AS users
FROM users
WHERE email IS NOT NULL
GROUP BY SPLIT_PART(LOWER(TRIM(email)), '@',2)
ORDER BY users DESC;
How SQL runs it, step by step:
1. FROM users: FROM reads users.
2. WHERE email IS NOT NULL: WHERE drops user 7.
3. GROUP BY SPLIT_PART(email, '@',2): GROUP BY works out each email's domain.
4. SELECT SPLIT_PART(email, '@',2) AS domain, COUNT(*) AS users: SELECT counts each pile.
5. ORDER BY users DESC: ORDER BY puts Gmail first, with 2, not 3.
Fix: SELECT SPLIT_PART(LOWER(TRIM(email)), '@',2) AS domain, COUNT(*) AS users: Run it again. Gmail 3, yahoo 2, proton 1.
Fix: GROUP BY SPLIT_PART(LOWER(TRIM(email)), '@',2): Same clean text in both places. All six emails counted.
Takeaway: Clean the text, then GROUP BY. LOWER(TRIM(email)) first, so one domain is one group.
Follow @visual.sql101 for a new visual SQL lesson every Monday, Wednesday and Friday.
#sql #learnsql #sqlchallenge #sqlinterview #dataanalyst #datacleaning #groupby #interviewprep #Shorts
Share this link via
Or copy link

























