'How can I make a MySQL SUM query return zero instead of null if there are no records?
Here is my select query:
SELECT SUM(rating) AS this_week
FROM table_name
WHERE UNIX_TIMESTAMP(created_at) >= UNIX_TIMESTAMP() - 604800)
Which basically counts the rating of an item for the last week (604800 is a number of seconds in 1 week).
The problem is that when there are no rows in the table, the this_week will be returned as NULL. I would like the query to return 0 in case there are no rows in the table. How to do it?
Solution 1:[1]
Can't you use IFNULL(SUM(rating), 0)?
Solution 2:[2]
Try this one : SUM(IFNULL(rating, 0))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | TheKojuEffect |
| Solution 2 | Kai - Kazuya Ito |
