Display only the duplicate column names appearing atleast thrice in MySQL


Use HAVING COUNT() for this. Let us first create a table −

mysql> create table DemoTable1351
    -> (
    -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
    -> StudentName varchar(40)
    -> );
Query OK, 0 rows affected (1.08 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1351(StudentName) values('Chris');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable1351(StudentName) values('Bob');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1351(StudentName) values('Bob');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1351(StudentName) values('David');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1351(StudentName) values('Bob');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1351(StudentName) values('David');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable1351(StudentName) values('Bob');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable1351(StudentName) values('Mike');
Query OK, 1 row affected (0.68 sec)
mysql> insert into DemoTable1351(StudentName) values('David');
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1351;

This will produce the following output −

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
|         1 | Chris       |
|         2 | Bob         |
|         3 | Bob         |
|         4 | David       |
|         5 | Bob         |
|         6 | David       |
|         7 | Bob         |
|         8 | Mike        |
|         9 | David       |
+-----------+-------------+
9 rows in set (0.00 sec)

Here is the query to display the duplicate column names appearing atleast thrice −

mysql> select * from DemoTable1351
    -> group by StudentName
    -> having count(StudentName) >=3;

This will produce the following output −

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
|         2 | Bob         |
|         4 | David       |
+-----------+-------------+
2 rows in set (0.00 sec)

Updated on: 05-Nov-2019

49 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements