Finding duplicate values in a SQL table
It's easy to find duplicates with one field:
SELECT name, COUNT(email)
FROM users
GROUP BY email
HAVING ( COUNT(email) > 1 )
So if we have a table
ID NAME EMAIL
1 John asd@asd.com
2 Sam asd@asd.com
3 Tom asd@asd.com
4 Bob bob@asd.com
5 Tom asd@asd.com
This query will give us John, Sam, Tom, Tom because they all have the same
email
.
However, what I want is to get duplicates with the same
email
and name
.
That is, I want to get "Tom", "Tom".
The reason I need this: I made a mistake, and allowed to insert duplicate
name
and email
values. Now I need to remove/change the duplicates, so I need to find them first.Answer:
SELECT
name, email, COUNT(*)
FROM
users
GROUP BY
name, email
HAVING
COUNT(*) > 1
Simply group on both of the columns.
Note: the ANSI standard is to have all non aggregated columns in the GROUP BY.
MySQL allows you to avoid this, but results are unpredictable:
- GROUP BY lname ORDER BY showing wrong results
- Which is the least expensive aggregate function in the absence of ANY() (see comments in accepted answer)
http://stackoverflow.com/questions/2594829/finding-duplicate-values-in-a-sql-table
COMMENTS