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;

Output

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;

Output

This will produce the following output −

+------+------+
| Name | freq |
+------+------+
| John | 3    |
+------+------+
1 row in set (0.00 sec)

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jun-2020

312 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements