There is a question about MySQL\'s COUNT() aggregate function that keeps popping into my head time to time. I would like to get some explanation to why it is working the way
COUNT(expression) counts the number of rows for which the expression is not NULL. The expression value=4 is only NULL if value is NULL, otherwise it is either TRUE (1) or FALSE (0), both of which are counted.
1 = 4 | FALSE
4 = 4 | TRUE
1 = 4 OR NULL | NULL
4 = 4 OR NULL | TRUE
You could use SUM instead:
SELECT SUM(value=4) FROM test
This is not particularly useful in your specific example but it can be useful if you want to count rows satisfying multiple different predicates using a single table scan such as in the following query:
SELECT
SUM(a>b) AS foo,
SUM(b>c) AS bar,
COUNT(*) AS total_rows
FROM test