views:

50

answers:

2

Suppose I have a column with words:

orange
grape
orange
orange
apple
orange
grape
banana

How do I execute a query to get the top 10 words, as well as their count?

+3  A: 
SELECT word, COUNT(*) word_cnt
FROM your_table
GROUP BY word
ORDER BY COUNT(*) DESC
LIMIT 10

The GROUP BY groups by values of word, the ORDER BY COUNT(*) DESC gets you the rows with highest count first, and the LIMIT 10 returns the first 10 rows only.

Peter Lang
+3  A: 
SELECT   word, COUNT(*) AS n
FROM     `table`
GROUP BY word
ORDER BY COUNT(*) DESC
LIMIT 10
Alnitak
nice. I had a related question about limit and performance. Does the query first get everything that matches and limit shows a subset of that? in other words, is using limit bad for performance?
darren
apparrently, no, at least sorting step is 'partial', see http://dev.mysql.com/doc/refman/5.1/en/limit-optimization.html
jonny