How to delete duplicates and leave one row in a table in MySQL?



To delete duplicates and leave one row in a table, you need to use the concept of temporary table. The steps are as follows −

create table anytemporaryTableName as select distinct yourColumnName1, yourColumnName2 from yourTableName;
truncate table yourTableName;
insert into yourTableName(yourColumnName1, yourColumnName2) select yourColumnName1, yourColumnName2 from yourtemporaryTableName ;
drop table yourtemporaryTableName ;

Let us create a table −

mysql> create table demo39
−> (
−> user_id int,
−> user_name varchar(20)
−> );
Query OK, 0 rows affected (0.74 sec)

Insert some records into the table with the help of insert command −

mysql> insert into demo39 values(10,'John');
Query OK, 1 row affected (0.19 sec)

mysql> insert into demo39 values(10,'John');
Query OK, 1 row affected (0.13 sec)

mysql> insert into demo39 values(11,'David');
Query OK, 1 row affected (0.20 sec)

mysql> insert into demo39 values(11,'David');
Query OK, 1 row affected (0.17 sec)

Display records from the table using select statement −

mysql> select *from demo39;

This will produce the following output −

+---------+-----------+
| user_id | user_name |
+---------+-----------+
|      10 | John      |
|      10 | John      |
|      11 | David     |
|      11 | David     |
+---------+-----------+
4 rows in set (0.00 sec)

Following is the query to delete duplicates and leave one row in a table −

mysql> create table temporaryTable as select distinct user_id, user_name from demo39;
Query OK, 2 rows affected (1.39 sec)
Records: 2 Duplicates: 0 Warnings: 0

mysql> truncate table demo39;
Query OK, 0 rows affected (2.30 sec)

mysql> insert into demo39(user_id, user_name) select user_id, user_name from temporaryTable;
Query OK, 2 rows affected (0.16 sec)
Records: 2 Duplicates: 0 Warnings: 0

mysql> drop table temporaryTable;
Query OK, 0 rows affected (1.01 sec)

Display records from the table using select statement −

mysql> select *from demo39;

This will produce the following output −

+---------+-----------+
| user_id | user_name |
+---------+-----------+
|      10 | John      |
|      11 | David     |
+---------+-----------+
2 rows in set (0.00 sec)

Advertisements