Count number of occurrences of records in a MySQL table and display the result in a new column?


For this, use COUNT(*) along with GROUP BY clause. Let us first create a table −

mysql> create table DemoTable1942
   (
   Value int
   );
Query OK, 0 rows affected (0.00 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1942 values(1);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1942 values(2);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1942 values(3);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1942 values(2);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1942 values(3);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1942 values(3);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1942 values(1);
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1942;

This will produce the following output −

+-------+
| Value |
+-------+
|     1 |
|     2 |
|     3 |
|     2 |
|     3 |
|     3 |
|     1 |
+-------+
7 rows in set (0.00 sec)

Here is the query to count number of occurrences:

mysql> select Value, count(*) from DemoTable1942
   group by Value;

This will produce the following output −

+-------+----------+
| Value | count(*) |
+-------+----------+
|     1 |        2 |
|     2 |        2 |
|     3 |        3 |
+-------+----------+
3 rows in set (0.00 sec)

Updated on: 31-Dec-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements