Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select most common value from a field in MySQL

Tags:

mysql

I have a table with a million rows, how do i select the most common(the value which appears most in the table) value from a field?

like image 912
dikidera Avatar asked Oct 07 '11 22:10

dikidera


People also ask

What is select * from in MySQL?

The SELECT statement is used to select data from a database. The data returned is stored in a result table, called the result-set.

How do I select top 10 rows in MySQL?

To select first 10 elements from a database using SQL ORDER BY clause with LIMIT 10. Insert some records in the table using insert command. Display all records from the table using select statement.


1 Answers

You need to group by the interesting column and for each value, select the value itself and the number of rows in which it appears.

Then it's a matter of sorting (to put the most common value first) and limiting the results to only one row.

In query form:

SELECT column, COUNT(*) AS magnitude  FROM table  GROUP BY column  ORDER BY magnitude DESC LIMIT 1 
like image 91
Jon Avatar answered Sep 20 '22 14:09

Jon