Find duplicates with GROUP BY and HAVING
To find duplicate values, GROUP BY the column that should be unique, so every copy lands in the same group. COUNT(*) tells you how big each group is, and HAVING COUNT(*) > 1 keeps only the groups with more than one row — those are your duplicates.
A tiny example
In plain English: Show me every email that appears on more than one customer, and how many times.
SELECT email, COUNT(*) AS copies
FROM customers
GROUP BY email
HAVING COUNT(*) > 1;Query result
| copies | |
|---|---|
| amara@mail.com | 2 |
| leo@mail.com | 3 |
Every other email appears once, so its group has a count of 1 and HAVING leaves it out. Only emails saved more than once appear in your results.
Common questions
- Why use HAVING instead of WHERE to find duplicates?
- WHERE runs before rows are grouped, so it can't see COUNT(*). HAVING runs after GROUP BY, so it can keep only the groups whose count is more than 1.
- How do I see how many copies each duplicate has?
- Put COUNT(*) in the SELECT list next to the grouped column, as in the example. Each duplicate value comes back once, with its number of copies beside it.
Related SQL lessons
Ready for a break?
A fresh, bite-sized SQL puzzle waits every morning. Tap tiles, see real results. No terminal, no setup, no timers.
Try today's free SQL puzzle