Monday, March 14, 2016

Delete all Duplicate Rows except for One in MySQL?


455down voteaccepted
1) 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
2) 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
I used this method in MySQL 5.1
Not sure about other versions.
NB - You need to do this first on a test copy of your table!

No comments:

Post a Comment