Tutorialspoint

Can I get the count of repeated values in a column with MySQL?


1 Answer
Kumar Varma

Yes, you can use ORDER BY DESC with GROUP BY. Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> PostMessage varchar(100)
   -> );
Query OK, 0 rows affected (0.69 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(PostMessage) values('Hi');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable(PostMessage) values('Hello');
Query OK, 1 row affected (0.16 sec)

mysql> insert into DemoTable(PostMessage) values('Hi');
Query OK, 1 row affected (0.12 sec)

mysql> insert into DemoTable(PostMessage) values('Awesome');
Query OK, 1 row affected (0.18 sec)

mysql> insert into DemoTable(PostMessage) values('Hello');
Query OK, 1 row affected (0.19 sec)

mysql> insert into DemoTable(PostMessage) values('Hi');
Query OK, 1 row affected (0.09 sec)

mysql> insert into DemoTable(PostMessage) values('Awesome');
Query OK, 1 row affected (0.33 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+-------------+
| Id | PostMessage |
+----+-------------+
|  1 | Hi          |
|  2 | Hello       |
|  3 | Hi          |
|  4 | Awesome     |
|  5 | Hello       |
|  6 | Hi          |
|  7 | Awesome     |
+----+-------------+
7 rows in set (0.00 sec)

Following is the query to get the highest amount of a value in a MySQL database −

mysql> select PostMessage,count(Id) from DemoTable group by PostMessage
    -> order by count(Id) DESC;

This will produce the following output −

+-------------+-----------+
| PostMessage | count(Id) |
+-------------+-----------+
| Hi          | 3 |
| Hello       | 2 |
| Awesome     | 2 |
+-------------+-----------+
3 rows in set (0.00 sec)

If you want only highest, you can use the following query −

mysql> select PostMessage,count(Id)  from DemoTable group by PostMessage having count(Id) > 2;

This will produce the following output −

+-------------+-----------+
| PostMessage | count(Id) |
+-------------+-----------+
| Hi          | 3         |
+-------------+-----------+
1 row in set (0.00 sec)

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.