Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Delete all Duplicate Rows except for One in MySQL?

How would I remove all duplicate data from a MySQL Table?

For example, with the following data:
SELECT * FROM names;

+----+--------+
| id | name |
+----+--------+
| 1 | google |
| 2 | yahoo |
| 3 | msn |
| 4 | google |
| 5 | google |
| 6 | yahoo |
+----+--------+


I would practiceSELECT DISTINCT name FROM names; if it were a SELECT query.

How would I do this with DELETE to only remove duplicates and keep just one record of each?
by

2 Answers

espadacoder11
If you want to keep the row with the lowest id value:

DELETE FROM NAMES
WHERE id NOT IN (SELECT
FROM (SELECT MIN(n.id)
FROM NAMES n
GROUP BY n.name) x)

If you want the id value that is the highest:

DELETE FROM NAMES
WHERE id NOT IN (SELECT

FROM (SELECT MAX(n.id)
FROM NAMES n
GROUP BY n.name) x)

The subquery in a subquery is necessary for MySQL, or you'll get a 1093 error.
RoliMishra
If you want to keep the row with the lowest id value:

DELETE n1 FROM names n1, names n2 WHERE n1.id > n2.id AND n1.name = n2.name


If you want to keep the row with the highest id value:

DELETE n1 FROM names n1, names n2 WHERE n1.id < n2.id AND n1.name = n2.name

Login / Signup to Answer the Question.