Finding Duplicate Rows in MySQL (Composite Key)?

MySQLMySQLi Database

To find duplicate rows, use GROUP BY and HAVING in MySQL. Let us first create a table −

mysql> create table DemoTable1494
   -> (
   -> ShippingDate datetime,
   -> CustomerCountryName varchar(20)
   -> );
Query OK, 0 rows affected (0.63 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1494 values('2018-09-10 12:34:50','US');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1494 values('2019-09-10 12:34:50','AUS');
Query OK, 1 row affected (0.65 sec)
mysql> insert into DemoTable1494 values('2018-09-10 11:00:00','US');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1494 values('2017-12-31 01:10:40','UK');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable1494 values('2019-09-10 05:00:50','AUS');
Query OK, 1 row affected (0.49 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1494;

This will produce the following output −

+---------------------+---------------------+
| ShippingDate        | CustomerCountryName |
+---------------------+---------------------+
| 2018-09-10 12:34:50 | US                  |
| 2019-09-10 12:34:50 | AUS                 |
| 2018-09-10 11:00:00 | US                  |
| 2017-12-31 01:10:40 | UK                  |
| 2019-09-10 05:00:50 | AUS                 |
+---------------------+---------------------+
5 rows in set (0.00 sec)

Following is the query to find duplicate rows in MySQL −

mysql> select ShippingDate,CustomerCountryName,count(*) as c
   -> from DemoTable1494
   -> group by date(ShippingDate),CustomerCountryName
   -> having c >=2
   -> order by c;

This will produce the following output −

+---------------------+---------------------+---+
| ShippingDate        | CustomerCountryName | c |
+---------------------+---------------------+---+
| 2018-09-10 12:34:50 | US                  | 2 |
| 2019-09-10 12:34:50 | AUS                 | 2 |
+---------------------+---------------------+---+
2 rows in set (0.00 sec)
raja
Published on 11-Dec-2019 10:05:49
Advertisements