How to remove Duplicate Records except a single record in MySQL?


You can use DELETE command with some condition for this since we need to keep one record and delete rest of the duplicate records.

Let us first create a table −

mysql> create table DemoTable
(
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentName varchar(40)
);
Query OK, 0 rows affected (0.48 sec)

Insert records in the table using insert command −

mysql> insert into DemoTable(StudentName) values('John');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable(StudentName) values('Carol');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable(StudentName) values('Sam');
Query OK, 1 row affected (0.28 sec)
mysql> insert into DemoTable(StudentName) values('Carol');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(StudentName) values('David');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable(StudentName) values('Carol');
Query OK, 1 row affected (0.26 sec)

Display records from the table using select command −

mysql> select *from DemoTable;

This will produce the following output −

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
| 1         | John        |
| 2         | Carol       |
| 3         | Sam         |
| 4         | Carol       |
| 5         | David       |
| 6         | Carol       |
+-----------+-------------+
6 rows in set (0.00 sec)

Here is the query to remove duplicate records except a single record −

mysql> delete tbl1 from DemoTable tbl1,DemoTable tbl2
WHERE
tbl1.StudentName = tbl2.StudentName AND tbl1.StudentId > tbl2.StudentId;
Query OK, 2 rows affected (0.79 sec)

The above query deleted 2 rows for “Carol” and left one of the “Carol” record. 

Let us now display the records of table −

mysql> select *from DemoTable;

This will produce the following output −

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
| 1         | John        |
| 2         | Carol       |
| 3         | Sam         |
| 5         | David       |
+-----------+-------------+
4 rows in set (0.00 sec)

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements