Duplicate emails
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
Write a query that returns every email that appears more than once in the users table, in a column named email. Each duplicated email should appear once in the result.
Rows can be returned in any order. Emails are compared exactly as stored.
Example
users
| id | |
|---|---|
| 1 | noa@mail.com |
| 2 | avi@mail.com |
| 3 | noa@mail.com |
Result:
| noa@mail.com |
Tip
WHERE filters rows before grouping. What filters groups after it?
Schema
CREATE TABLE users (
id INT PRIMARY KEY,
email TEXT NOT NULL
);Approach
Group the rows by email and keep the groups with more than one row:
SELECT email
FROM users
GROUP BY email
HAVING COUNT(*) > 1;HAVING is WHERE for groups. You cannot write WHERE COUNT(*) > 1, because WHERE runs before GROUP BY, when there are no groups to count yet. The logical order is FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT.
Alternatives
A self join also works, but needs DISTINCT and compares every pair of rows:
SELECT DISTINCT a.email
FROM users a
JOIN users b ON a.email = b.email AND a.id <> b.id;Follow-ups
- Delete the duplicates, keep the lowest id:
DELETE FROM users a USING users b WHERE a.email = b.email AND a.id > b.id; - Case-insensitive duplicates: group by
LOWER(email). To prevent them, add a unique index onLOWER(email).
Reference solution
SELECT email
FROM users
GROUP BY email
HAVING COUNT(*) > 1;