Why do I need “OR NULL” in MySQL when counting rows with a condition

This should reveal all

SELECT 4=4, 3=4, 1 or null, 0 or null

Output

1   |   0   |   1   |   NULL

Facts

  1. COUNT adds up the columns / expressions that evaluate to NOT NULL. Anything will increment by 1, as long as it is not null. Exception is COUNT(DISTINCT) where it increments only if it is not already counted.

  2. When a BOOLEAN expression is used on its own, it returns either 1 or 0.

  3. When a boolean is OR-ed with NULL, it is NULL only when it is 0 (false)

To others

Yes if the count is the ONLY column desired, one could use WHERE value=4 but if it is a query that wants to count the 4’s as well as retrieving other counts/aggregates, then the filter doesn’t work. An alternative would have been SUM(value=4), e.g.

SELECT sum(value=4)
  FROM test

Leave a Comment