Count the occurrences of specific records (duplicate) in one MySQL query


For this, use aggregate function COUNT() and GROUP BY to group those specific records for occurrences. Let us first create a table −

mysql> create table DemoTable
(
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentSubject varchar(40)
);
Query OK, 0 rows affected (5.03 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(StudentSubject) values('MySQL');
Query OK, 1 row affected (0.78 sec)
mysql> insert into DemoTable(StudentSubject) values('Java');
Query OK, 1 row affected (0.39 sec)
mysql> insert into DemoTable(StudentSubject) values('MySQL');
Query OK, 1 row affected (1.12 sec)
mysql> insert into DemoTable(StudentSubject) values('MongoDB');
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable(StudentSubject) values('Java');
Query OK, 1 row affected (0.45 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-----------+----------------+
| StudentId | StudentSubject |
+-----------+----------------+
|         1 | MySQL          |
|         2 | Java           |
|         3 | MySQL          |
|         4 | MongoDB        |
|         5 | Java           |
+-----------+----------------+
5 rows in set (0.00 sec)

Following is the query to count the occurrences of specific records (duplicate) in one MySQL query −

mysql> select StudentSubject,count(StudentId) from DemoTable group by StudentSubject;

This will produce the following output −

+----------------+------------------+
| StudentSubject | count(StudentId) |
+----------------+------------------+
| MySQL          |                2 |
| Java           |                2 |
| MongoDB        |                1 |
+----------------+------------------+
3 rows in set (0.00 sec)

Updated on: 09-Oct-2019

79 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements