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?
            Asked
            
        
        
            Active
            
        
            Viewed 5.6k times
        
    3 Answers
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.
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