mysql – SQL query to remove duplicates from a table by one field

Question:

There is a table with duplicates in MySQL: (by the name field)

id |  name | surname
--------------------
1  | niko  | surname
2  | niko  | surname
3  | jane  | surname
4  | jane  | surname
5  | ivan  | surname

You need to get a table of this kind

id |  name | surname
--------------------
1  | niko  | surname
3  | jane  | surname
5  | ivan  | surname

Answer:

Query for the resulting table:

SELECT min(id), name, surname
FROM `table`
GROUP BY name, surname

To remove duplicates, the following technique is suitable:

CREATE TEMPORARY TABLE `t_temp` 
as  (
   SELECT min(id) as id
   FROM `table`
   GROUP BY name, surname
);

DELETE from `table`
WHERE `table`.id not in (
   SELECT id FROM t_temp
);

There are of course nuances …

Scroll to Top