Find rows that have the same value on a column in MySQL?

MySQLMySQLi Database

First, we will create a table and insert some values into the table. Let us create a table.

mysql> create table RowValueDemo
   -> (
   -> Name varchar(100)
   -> );
Query OK, 0 rows affected (0.69 sec)

Insert records using the insert command. We have added duplicate values as well for our example.

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

mysql> insert into RowValueDemo values('Bob');
Query OK, 1 row affected (0.14 sec)

mysql> insert into RowValueDemo values('Carol');
Query OK, 1 row affected (0.11 sec)

mysql> insert into RowValueDemo values('John');
Query OK, 1 row affected (0.24 sec)

mysql> insert into RowValueDemo values('John');
Query OK, 1 row affected (0.09 sec)

mysql> insert into RowValueDemo values('John');
Query OK, 1 row affected (0.10 sec)

mysql> insert into RowValueDemo values('Bob');
Query OK, 1 row affected (0.09 sec)

mysql> insert into RowValueDemo values('Bob');
Query OK, 1 row affected (0.18 sec)

Displaying all records with the help of select statement.

mysql> select *from RowValueDemo;

Here is the output.

+-------+
| Name  |
+-------+
| John  |
| Bob   |
| Carol |
| John  |
| John  |
| John  |
| Bob   |
| Bob   |
+-------+
8 rows in set (0.00 sec)

Now, we ill get only the rows that have same value for column using the following query −

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

The following is the output.

+------+
| Name |
+------+
| John |
| Bob  |
| John |
| John |
| John |
| Bob  |
| Bob  |
+------+
7 rows in set (0.06 sec)
raja
Published on 29-Nov-2018 11:02:08
Advertisements