How to remove duplicate values from a MySQL table using LEFT JOIN?


Let us first create a table −

mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   FirstName varchar(100)
);
Query OK, 0 rows affected (0.46 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(FirstName) values('Chris');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable(FirstName) values('Robert');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(FirstName) values('Robert');
Query OK, 1 row affected (0.07 sec)
mysql> insert into DemoTable(FirstName) values('John');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(FirstName) values('John');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable(FirstName) values('Mike');
Query OK, 1 row affected (0.09 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+-----------+
| Id | FirstName |
+----+-----------+
|  1 | Chris     |
|  2 | Robert    |
|  3 | Robert    |
|  4 | John      |
|  5 | John      |
|  6 | Mike      |
+----+-----------+
6 rows in set (0.00 sec)

Following is the query to remove duplicate values from MySQL table −

mysql> delete tbl from DemoTable tbl
left join(
   select min(Id) as Id, FirstName
   from DemoTable
   group by FirstName
) tbl1 ON tbl.Id = tbl1.Id AND tbl.FirstName = tbl1.FirstName
where tbl1.Id IS NULL;
Query OK, 2 rows affected (0.16 sec)

Let us check table records once again.

mysql> select *from DemoTable;

This will produce the following output −

+----+-----------+
| Id | FirstName |
+----+-----------+
|  1 | Chris     |
|  2 | Robert    |
|  4 | John      |
|  6 | Mike      |
+----+-----------+
4 rows in set (0.00 sec)

Updated on: 24-Sep-2019

473 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements