How can I make a MySQL SUM query return zero instead of null if there are no records?
This should do the trick:
SELECT COALESCE(SUM(rating),0) AS this_week FROM table_name
WHERE UNIX_TIMESTAMP(created_at) >= UNIX_TIMESTAMP() - 604800)
COALESCE is a function that will return the first non NULL value from the list.
Can't you use IFNULL(SUM(rating), 0)
?