39

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?

dikidera
  • 2,004
  • 6
  • 29
  • 36

3 Answers3

106

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
Jon
  • 428,835
  • 81
  • 738
  • 806
26

This thread should shed some light on your issue.

Basically, use COUNT() with a GROUP BY clause:

SELECT foo, COUNT(foo) AS fooCount 
FROM table
GROUP BY foo
ORDER BY fooCount DESC

And to get only the first result (most common), add

LIMIT 1

To the end of your query.

sMyles
  • 2,418
  • 1
  • 30
  • 44
Bojangles
  • 99,427
  • 50
  • 170
  • 208
7

In case you don't need to return the frequency of the most common value, you could use:

SELECT foo
FROM table
GROUP BY foo
ORDER BY COUNT(foo) DESC
LIMIT 1 

This has the additional benefit of only returning one column and therefore working in subqueries.

Philip
  • 157
  • 2
  • 8