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?
If you use the SUM() function in a SELECT statement that returns no row, the SUM() function returns NULL , not zero. The DISTINCT option instructs the SUM() function to calculate the sum of only distinct values in a set. The SUM() function ignores the NULL values in the calculation.
The SUM function returns the sum of the input column or expression values. The SUM function works with numeric values and ignores NULL values.
If there are no rows, sum() will return null . It will also return null if all rows have a null balance.
Use IFNULL or COALESCE() function in order to convert MySQL NULL to 0. Insert some records in the table using insert command. Display all records from the table using select statement.
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)
?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With