MySQL query to find duplicate tuples and display the count?


To find duplicate tuples, use GROUP BY HAVING clause. Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Id int,
   -> Name varchar(20)
   -> );
Query OK, 0 rows affected (0.80 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(100,'Chris');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(101,'David');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable values(101,'Mike');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(100,'Carol');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values(100,'Chris');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(100,'Chris');
Query OK, 1 row affected (0.10 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable;

This will produce the following output −

+------+-------+
|   Id | Name  |
+------+-------+
|  100 | Chris |
|  101 | David |
|  101 | Mike  |
|  100 | Carol |
|  100 | Chris |
|  100 | Chris |
+------+-------+
6 rows in set (0.00 sec)

Following is the query to find duplicate tuples −

mysql> select Id,Name,count(*) as t from DemoTable
   -> group by Id,Name
   -> having count(*) > 2;

This will produce the following output −

+------+-------+---+
| Id   | Name  | t |
+------+-------+---+
| 100  | Chris | 3 |
+------+-------+---+
1 row in set (0.03 sec)

Updated on: 26-Feb-2020

456 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements