I have an expense table where multiple expenses can be tied to an ID, but each of these expenses can have a specific type.
I can get the sum of ONE type.
SELECT
SUM(expense) AS total
FROM expenses
WHERE id = 1 AND type = 'cleaning';
But I would like to get the sum of an expense that has two types, so I tried
SELECT
SUM(expense) AS total
FROM expenses
WHERE id = 1
AND type = 'cleaning'
AND type = 'painting';
I expected this to return 3000, but instead it returns NULL.
Why does the AND operator not work in this instance?
3
Answers
A
where
clause is evaluated for each row. There is no row for which:Because the
sum
sees no rows, it returnsnull
.It is because according to the query, you are searching for a type that has both painting and cleaning.
You can rather try using OR for getting the sum of painting and cleaning.
Your
query says that you want to
SUM
theexpense
of all records whoseType
equalscleaning
andpainting
at the same time.Since
Type
either does not match either of those values, or it matches exactly one of them, whereas your criteria expects it to match both, none of the records matches the criteria, so yourSUM
computes the sum of empty set.Try:
or
instead.