250

I have an SQL table called "posts" that looks like this:

id | category
-----------------------
1  | 3
2  | 1
3  | 4
4  | 2
5  | 1
6  | 1
7  | 2

Each category number corresponds to a category. How would I go about counting the number of times each category appears on a post all in one SQL query?

As an example, such a query might return a symbolic array such as this: (1:3, 2:2, 3:1, 4:1)

My current method is to use queries for each possible category, such as: SELECT COUNT(*) AS num FROM posts WHERE category=#, and then combine the return values into a final array. However, I'm looking for a solution that uses only one query.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Jeff Gortmaker
  • 4,607
  • 3
  • 22
  • 29

1 Answers1

432
SELECT
  category,
  COUNT(*) AS `num`
FROM
  posts
GROUP BY
  category
Dan Grossman
  • 51,866
  • 10
  • 112
  • 101
  • 4
    @MichelAyres: source? – Moberg Dec 03 '14 at 13:48
  • 5
    "That is, the ANSI standard recognises it as bleeding obvious what you mean. COUNT(1) has been optimised out by RDBMS vendors because of this superstition. Otherwise it would be evaluated as per ANSI" [Count(*) vs Count(1)](http://stackoverflow.com/a/1221649/662581) – Michel Ayres Dec 03 '14 at 17:42
  • @Moberg It was how I learned (old people teaching superstitions ...). Here is a small part of [the chat](http://chat.stackexchange.com/transcript/message/18884568#18884568) for a discussion about it – Michel Ayres Dec 03 '14 at 18:11
  • 1
    Tried that [here](http://www.w3schools.com/sql/trysql.asp?filename=trysql_select_orderby2) and it didn't work. – CGTheLegend May 13 '15 at 09:00
  • 2
    It works "there" when you use column and table names that exist in the example. – Dan Grossman Jun 12 '15 at 17:07
  • @DanGrossman will you please guide me in this question http://stackoverflow.com/questions/32136843/fetch-data-from-mysql-database-on-the-basis-of-leave-types-such-as-exam-unpaid – Muddasir Abbas Aug 21 '15 at 09:31
  • @MichelAyres This is old, but your source actually says that there is no difference in performance. It doesn't support your statement. – Bpainter May 19 '16 at 21:37
  • I have to remove the backticks around '`num`', but then it works. (i.e. just "COUNT(*) AS num") – David Doria May 06 '21 at 16:25