MySQL query to count the duplicate ID values and display the result in a separate column


To count the duplicate ID values, use aggregate function COUNT() and GROUP BY. Let us first create a table −

mysql> create table DemoTable
(
   Id int,
   Name varchar(100)
);
Query OK, 0 rows affected (1.30 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(50,'Chris');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values(51,'David');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(51,'Mike');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values(50,'Sam');
Query OK, 1 row affected (0.17 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+------+-------+
| Id   | Name  |
+------+-------+
|   50 | Chris |
|   51 | David |
|   51 | Mike  |
|   50 | Sam   |
+------+-------+
4 rows in set (0.00 sec)

Following is the query to display the count of duplicate ID values in a new column −

mysql> select Id,count(Name) as Count
   from DemoTable
   group by Id;

This will produce the following output −

+------+-------+
| Id   | Count |
+------+-------+
|   50 |     2 |
|   51 |     2 |
+------+-------+
2 rows in set (0.00 sec)

Updated on: 01-Oct-2019

684 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements