Return the field with highest count in MySQL


To return the field with highest count, use ORDER BY COUNT(*). Let us first create a table −

mysql> create table DemoTable1940
   (
   FirstName varchar(20)
   );
Query OK, 0 rows affected (0.00 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1940 values('Chris');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1940 values('Mike');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1940 values('Adam');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1940 values('Mike');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1940 values('Chris');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1940 values('David');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1940 values('Mike');
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1940;

This will produce the following output −

+-----------+
| FirstName |
+-----------+
| Chris     |
| Mike      |
| Adam      |
| Mike      |
| Chris     |
| David     |
| Mike      |
+-----------+
7 rows in set (0.00 sec)

Here is the query to return the field with highest count:

mysql> select * from DemoTable1940
   group by FirstName
   order by count(*) desc
   limit 1;

This will produce the following output −

+-----------+
| FirstName |
+-----------+
| Mike      |
+-----------+
1 row in set (0.00 sec)

Updated on: 30-Dec-2019

978 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements