In other words, "Select all animals for which the number of matching names that do not meet the IN ('homer','bart','marge','lisa','maggie') condition IN ('homer','bart','marge','lisa','maggie') is 0 .
Thus, it can also be implemented as follows:
SELECT animal FROM pets GROUP BY animal HAVING COUNT(name NOT IN ('homer','bart','marge','lisa','maggie') OR NULL) = 0
This expression
name NOT IN ('homer','bart','marge','lisa','maggie') OR NULL
leads to either 1 or NULL , which leads to the fact that COUNT should be considered the corresponding occurrence of name or omit it. (As for why OR NULL is and how the whole expression works, I will refer to this question: Why do I need "OR NULL" in MySQL when counting rows with a condition .)
As you can see, as an alternative, you can use SUM to do the same, and the expression for SUM seems to be shorter since OR NULL not needed there. I usually prefer COUNT() to SUM() when I need to count things, rather than add arbitrary values. But, as far as I know, there are no advantages over each other, so which function to use depends on your personal preferences / tastes.
Andriy m
source share