I have a database with the following table “responses” with an id and a U.S. state:
*id *state
1 CA
2 NY
3 NY
4 CO
5 DE
I’m using PHP to output the total number of rows for each of the 50 states in the U.S.
So, my output would look like:
CA: 1
NY: 2
CO: 1
DE: 1
etc…
I know I can run 50 queries like so:
SELECT *
FROM `responses`
WHERE state='CA'
My question is: is there a more efficient way to handle this, or do I need to run 50 queries?
Use a
GROUP BYclause:There are many good tutorials on using GROUP BY, and it’s one of the most useful and powerful features of SQL.