EN
MySQL - delete all duplicated rows except one
0 points
In this article, we would like to show you how to delete duplicated rows except one in MySQL.
Quick solution:
xxxxxxxxxx
1
DELETE n1
2
FROM `users` n1, `users` n2
3
WHERE n1.id > n2.id AND n1.name = n2.name
To show how to delete duplicated rows except one, we will use the following users
table:

Note:
At the end of this article you can find database preparation SQL queries.
In this example, we will delete all the rows with duplicated name except one, with the lowest id
value.
Query:
xxxxxxxxxx
1
DELETE n1
2
FROM `users` n1, `users` n2
3
WHERE n1.id > n2.id AND n1.name = n2.name;
Result:

In this example, we will delete all the rows with duplicated name except one, with the highest id
value.
Query:
xxxxxxxxxx
1
DELETE n1
2
FROM `users` n1, `users` n2
3
WHERE n1.id < n2.id AND n1.name = n2.name;
Result:

create_tables.sql
file:
xxxxxxxxxx
1
CREATE TABLE `users` (
2
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
3
`name` VARCHAR(100) NOT NULL,
4
`email` VARCHAR(100) NOT NULL,
5
`country` VARCHAR(15) NOT NULL,
6
PRIMARY KEY (`id`)
7
)
8
ENGINE=InnoDB;
insert_data.sql
file:
xxxxxxxxxx
1
INSERT INTO `users`
2
(`name`, `email`, `country`)
3
VALUES
4
('Tom', 'tom1@email.com', 'Poland'),
5
('Tom', 'tom2@email.com', 'Poland'),
6
('Tom', 'tom3@email.com', 'Poland'),
7
('Kim', 'kim1@email.com', 'Vietnam'),
8
('Kim', 'kim2@email.com', 'Vietnam'),
9
('Chris', 'chris1@email.com', 'Spain'),
10
('Chris', 'chris2@email.com', 'Spain'),
11
('Chris', 'chris3@email.com', 'USA');