To select only duplicate records from database and display the count, use HAVING along with aggregate function count(). Let us first create a table −
mysql> create table duplicateRecords -> ( -> ClientId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> ClientName varchar(20) -> ); Query OK, 0 rows affected (0.49 sec)
Following is the query to insert records in the table using insert command −
mysql> insert into duplicateRecords(ClientName) values('John'); Query OK, 1 row affected (0.16 sec) mysql> insert into duplicateRecords(ClientName) values('Carol'); Query OK, 1 row affected (0.17 sec) mysql> insert into duplicateRecords(ClientName) values('John'); Query OK, 1 row affected (0.29 sec) mysql> insert into duplicateRecords(ClientName) values('Sam'); Query OK, 1 row affected (0.19 sec) mysql> insert into duplicateRecords(ClientName) values('Sam'); Query OK, 1 row affected (0.11 sec) mysql> insert into duplicateRecords(ClientName) values('Bob'); Query OK, 1 row affected (0.12 sec) mysql> insert into duplicateRecords(ClientName) values('John'); Query OK, 1 row affected (0.13 sec) mysql> insert into duplicateRecords(ClientName) values('Sam'); Query OK, 1 row affected (0.12 sec)
Following is the query to display all records from the table using select statement −
mysql> select * from duplicateRecords;
This will produce the following output −
+----------+------------+ | ClientId | ClientName | +----------+------------+ | 1 | John | | 2 | Carol | | 3 | John | | 4 | Sam | | 5 | Sam | | 6 | Bob | | 7 | John | | 8 | Sam | +----------+------------+ 8 rows in set (0.00 sec)
Following is the query:to select only duplicate records from database −
mysql> select ClientName,count(*) as DuplicateRecord -> from duplicateRecords -> group by ClientName -> having DuplicateRecord > 1;
This will produce the following output −
+------------+-----------------+ | ClientName | DuplicateRecord | +------------+-----------------+ | John | 3 | | Sam | 3 | +------------+-----------------+ 2 rows in set (0.00 sec)