Find and display duplicate records in MySQL?

MySQLMySQLi Database

First, a table is created with the help of the CREATE command. This is given as follows −

mysql> CREATE table DuplicateFound
-> (
-> ID int,
-> Name varchar(100),
-> Location varchar(200)
-> );
Query OK, 0 rows affected (0.45 sec)

After creating the table, the records are inserted with the help of the INSERT command as follows −

mysql> INSERT into DuplicateFound values(1,'John','US');
Query OK, 1 row affected (0.10 sec)

mysql> INSERT into DuplicateFound values(2,'Bob','UK');
Query OK, 1 row affected (0.18 sec)

mysql> INSERT into DuplicateFound values(3,'David','US');
Query OK, 1 row affected (0.14 sec)

mysql> INSERT into DuplicateFound values(4,'Smith','US');
Query OK, 1 row affected (0.16 sec)

mysql> INSERT into DuplicateFound values(5,'Carol','UK');
Query OK, 1 row affected (0.16 sec)

The records are displayed with the help of the SELECT statement. This is given below −

mysql> SELECT * from DuplicateFound;

The following is the output obtained −

+------+-------+----------+
| ID   | Name  | Location |
+------+-------+----------+
| 1    | John  | US       |
| 2    | Bob   | UK       |
| 3    | David | US       |
| 4    | Smith | US       |
| 5    | Carol | UK       |
+------+-------+----------+
5 rows in set (0.00 sec)

The query to find and display the duplicate records together is given as follows −

mysql> SELECT * from DuplicateFound
-> where location in (select location from DuplicateFound group by location having count(location) >1 )
-> order by location;

The following is the output obtained

+------+-------+----------+
| ID   | Name  | Location |
+------+-------+----------+
| 2    | Bob   | UK       |
| 5    | Carol | UK       |
| 1    | John  | US       |
| 3    | David | US       |
| 4    | Smith | US       |
+------+-------+----------+
5 rows in set (0.06 sec)

We can display those records which belong to a single location. This is given as follows −

mysql> select Name,location from DuplicateFound
-> group by location
-> having count(location) > 1;

The following is the output

+------+----------+
| Name | Location |
+------+----------+
| John | US       |
| Bob   | UK      |
+------+----------+
2 rows in set (0.04 sec)
raja
Published on 18-Oct-2018 13:34:27
Advertisements