How to select all duplicates in MySQL?

MySQLMySQLi Database

To select duplicates, you can use subquery. Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Name varchar(100)
   -> );
Query OK, 0 rows affected (0.87 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(Name) values('John');
Query OK, 1 row affected (0.16 sec)

mysql> insert into DemoTable(Name) values('Chris');
Query OK, 1 row affected (0.21 sec)

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

mysql> insert into DemoTable(Name) values('David');
Query OK, 1 row affected (0.13 sec)

mysql> insert into DemoTable(Name) values('Bob');
Query OK, 1 row affected (0.15 sec)

mysql> insert into DemoTable(Name) values('Chris');
Query OK, 1 row affected (0.16 sec)

mysql> insert into DemoTable(Name) values('Mike');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable(Name) values('Robert');
Query OK, 1 row affected (0.11 sec)

mysql> insert into DemoTable(Name) values('Mike');
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

+----+--------+
| Id | Name   |
+----+--------+
| 1  | John   |
| 2  | Chris  |
| 3  | John   |
| 4  | David  |
| 5  | Bob    |
| 6  | Chris  |
| 7  | Mike   |
| 8  | Robert |
| 9  | Mike   |
+----+--------+
9 rows in set (0.00 sec)

Following is the query to select all duplicates −

mysql> select *from DemoTable
   -> where Name in (select Name from DemoTable group by Name having count(*) > 1);

Output

+----+-------+
| Id | Name  |
+----+-------+
| 1  | John  |
| 2  | Chris |
| 3  | John  |
| 6  | Chris |
| 7  | Mike  |
| 9  | Mike  |
+----+-------+
6 rows in set (0.09 sec)
raja
Published on 10-Jul-2019 15:07:48
Advertisements