Find duplicate emails
Task
Return every email that appears more than once in users, with how many times it appears. Columns: email, n.
Row order does not matter. Column names do not have to match. SQLite dialect.
Tables
users
id INTEGER, email TEXT
| id | |
|---|---|
| 1 | asha@mail.com |
| 2 | ben@mail.com |
| 3 | asha@mail.com |
| 4 | chen@mail.com |
| 5 | ben@mail.com |
| 6 | asha@mail.com |
| 7 | dev@mail.com |
- Group the rows by email.
- Filter groups with HAVING, which runs after GROUP BY. WHERE cannot see COUNT(*).
Expected output
| n | |
|---|---|
| asha@mail.com | 3 |
| ben@mail.com | 2 |
Show solution
SQL
SELECT email, COUNT(*) AS n
FROM users
GROUP BY email
HAVING COUNT(*) > 1;WHERE filters rows before grouping; HAVING filters groups after aggregation, so the count condition belongs in HAVING.
Why this works
WHERE filters rows before grouping; HAVING filters groups after aggregation, so the count condition belongs in HAVING.