MySQL Count and Group By

Last updated on

If you have a table called colors:

id         color
----------------
1          red
2          red
3          green
3          green
4          green
5          blue

And want to group and count all colors to create this:

color      count
----------------
red        2
green      3
blue       1

Try the following.

SELECT color, COUNT( * ) 
FROM colors
GROUP BY color
ORDER BY COUNT( * ) DESC 

Let me know in the comments if this helped. Follow me @DevAnswers or read more.

1 Star2 Stars3 Stars4 Stars5 Stars

Feedback

Your email address will not be published. Required fields are marked *

We use Markdown to style comments, like on Github and Reddit.
To do a line break, type two spaces after the sentence.
You can add inline code by wrapping it in backticks: `code here`

    To do an entire block of code  
    type four spaces before the line
    and it will appear in a block like this.
    <-- four empty spaces