Get the maximum count of distinct values in a separate column with MySQL


Use COUNT() function along with GROUP BY clause for this. Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Name varchar(100)
   -> );
Query OK, 0 rows affected (0.69 sec)

Insert some records in the table using insert command −

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

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

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

mysql> insert into DemoTable values('Mike');
Query OK, 1 row affected (0.17 sec)

mysql> insert into DemoTable values('John');
Query OK, 1 row affected (0.25 sec)

mysql> insert into DemoTable values('Sam');
Query OK, 1 row affected (0.24 sec)

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

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-------+
| Name  |
+-------+
| John  |
| Sam   |
| John  |
| Mike  |
| John  |
| Sam   |
| Carol |
+-------+
7 rows in set (0.00 sec)

Here is the query to maximum count of distinct values in SQL −

mysql> select Name, count(*) as freq from DemoTable group by Name order by count(*) desc limit 1;

This will produce the following output −

+------+------+
| Name | freq |
+------+------+
| John | 3    |
+------+------+
1 row in set (0.00 sec)
raja
Published on 10-Jul-2019 17:19:08
Advertisements