How to find duplicate value pairs in MySQL?

MySQLMySQLi Database

To find duplicate value pairs in MySQL, use GROUP BY HAVING clause.

Let us first create a table −

mysql> create table DemoTable748 (Id int, FirstName varchar(100));
Query OK, 0 rows affected (0.46 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable748 values(100,'John');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable748 values(100,'Sam');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable748 values(200,'Carol');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable748 values(200,'Carol');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable748 values(300,'Mike');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable748 values(300,'Sam');
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable748;

This will produce the following output -

+------+-----------+
| Id   | FirstName |
+------+-----------+
|  100 | John      |
|  100 | Sam       |
|  200 | Carol     |
|  200 | Carol     |
|  300 | Mike      |
|  300 | Sam       |
+------+-----------+
6 rows in set (0.00 sec)

Following is the query to find duplicate value pairs in MySQL −

mysql> select Id from DemoTable748
   group by Id,FirstName having count(*)=2;

This will produce the following output. Since the only duplicate value pair for Id and FirstName is 200, therefore the output displays the same −

+------+
| Id   |
+------+
| 200  | 
+------+
1 row in set (0.00 sec)
raja
Published on 03-Sep-2019 07:32:28
Advertisements