Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a MySQL SUM query return zero instead of null if there are no records?

Tags:

sql

mysql

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?

like image 797
Richard Knop Avatar asked Aug 23 '09 14:08

Richard Knop


People also ask

Does sum ignore NULL values MySQL?

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.

Does sum Ignore NULL?

The SUM function returns the sum of the input column or expression values. The SUM function works with numeric values and ignores NULL values.

Does sum return NULL?

If there are no rows, sum() will return null . It will also return null if all rows have a null balance.

How do I make NULL 0 in MySQL?

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.


2 Answers

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.

like image 89
Jimmy Stenke Avatar answered Oct 12 '22 20:10

Jimmy Stenke


Can't you use IFNULL(SUM(rating), 0)?

like image 26
CMerat Avatar answered Oct 12 '22 20:10

CMerat