How to delete all the duplicate records in a MySQL table?

MySQLMySQLi Database

To delete duplicate records from a table, we can use the DELETE command. Let us now create a table.

mysql> create table DuplicateDeleteDemo
   -> (
   -> id int,
   -> name varchar(100)
   -> );
Query OK, 0 rows affected (0.60 sec)

Inserting records into the table “DuplicateDeleteDemo”: Here, we have added “John” as duplicate record 3 times.

mysql> insert into DuplicateDeleteDemo values(1,'John');
Query OK, 1 row affected (0.11 sec)

mysql>  insert into DuplicateDeleteDemo values(1,'John');
Query OK, 1 row affected (0.14 sec)

mysql>  insert into DuplicateDeleteDemo values(2,'Johnson');
Query OK, 1 row affected (0.13 sec)

mysql>  insert into DuplicateDeleteDemo values(1,'John');
Query OK, 1 row affected (0.14 sec)

To display all records, use the SELECT statement.

mysql> select *from DuplicateDeleteDemo;

The following is the output with duplicate records.

+------+---------+
| id   | name    |
+------+---------+
|    1 | John    |
|    1 | John    |
|    2 | Johnson |
|    1 | John    |
+------+---------+
4 rows in set (0.00 sec)

In the above output, we have 4 records in the table, out of which 3 records are duplicate.

To delete duplicate records, ude DELETE.

mysql> delete from DuplicateDeleteDemo where id=1;
Query OK, 3 rows affected (0.19 sec)

To check if records have been deleted, let us again display all the records.

mysql> select *from DuplicateDeleteDemo;

The following output displays that all the duplicate records have been deleted.

+------+---------+
| id   | name    |
+------+---------+
|    2 | Johnson |
+------+---------+
1 row in set (0.00 sec)
raja
Published on 22-Nov-2018 17:41:07
Advertisements