MySQL - What is the difference between SUM and COUNT?
It is a big difference because the result is not the same.
The first query returns the number of times the condition is true, because true
is 1
and false
is 0
.
The second query returns the complete record count because count()
does not care about the content inside it, as long as the content is NOT NULL. Because count(1)
and count(0)
are still values and both get counted.
To get the correct return value for the second query you would have to make the result of the condition be null
(instead of 0
) to not being counted. Like this:
SELECT COUNT(case when USER_NAME = 'JoeBlow' then 'no matter what' else NULL end)
from your_table
Or simply remove the else
part from the case
statement which automatically makes the else
part null
.
To answer the OP question more direct and literal, consider if you were totalling integers in your column instead of strings.
+----+------+
| id | vote |
+----+------+
| 1 | 1 |
| 2 | -1 |
| 3 | 1 |
| 4 | -1 |
| 5 | 1 |
+----+------+
COUNT = 5 votes
SUM = 1 vote
(-2 + 3 = 1)
Sum is doing the mathematical sum, whereas count simply counts any value as 1 regardless of what data type.
I guess COUNT() returns the number of rows in a column whereas SUM() returns the sum for the column