MySQL Select where value exists more than once

MySQLMySQLi Database

For this, you can use GROUP BY HAVING along with the COUNT(*) function. Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Value int
   -> );
Query OK, 0 rows affected (0.47 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(20);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values(10);
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable values(30);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values(10);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(30);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values(40);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values(50);
Query OK, 1 row affected (0.27 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-------+
| Value |
+-------+
|    20 |
|    10 |
|    30 |
|    10 |
|    30 |
|    40 |
|    50 |
+-------+
7 rows in set (0.00 sec)

Following is the query to select where value exists more than once −

mysql> select *from DemoTable
   -> group by Value
   -> having count(*) > 1;

This will produce the following output −

+-------+
| Value |
+-------+
|    10 |
|    30 |
+-------+
2 rows in set (0.38 sec)
raja
Published on 13-Dec-2019 10:09:40
Advertisements