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.

Answer from Jimmy Stenke on Stack Overflow
Top answer
1 of 4
390

Use COALESCE to avoid that outcome.

SELECT COALESCE(SUM(column),0)
FROM   table
WHERE  ...

To see it in action, please see this sql fiddle: http://www.sqlfiddle.com/#!2/d1542/3/0


More Information:

Given three tables (one with all numbers, one with all nulls, and one with a mixture):

SQL Fiddle

MySQL 5.5.32 Schema Setup:

CREATE TABLE foo
(
  id    INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  val   INT
);

INSERT INTO foo (val) VALUES
(null),(1),(null),(2),(null),(3),(null),(4),(null),(5),(null),(6),(null);

CREATE TABLE bar
(
  id    INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  val   INT
);

INSERT INTO bar (val) VALUES
(1),(2),(3),(4),(5),(6);

CREATE TABLE baz
(
  id    INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  val   INT
);

INSERT INTO baz (val) VALUES
(null),(null),(null),(null),(null),(null);

Query 1:

SELECT  'foo'                   as table_name,
        'mixed null/non-null'   as description,
        21                      as expected_sum,
        COALESCE(SUM(val), 0)   as actual_sum
FROM    foo
UNION ALL

SELECT  'bar'                   as table_name,
        'all non-null'          as description,
        21                      as expected_sum,
        COALESCE(SUM(val), 0)   as actual_sum
FROM    bar
UNION ALL

SELECT  'baz'                   as table_name,
        'all null'              as description,
        0                       as expected_sum,
        COALESCE(SUM(val), 0)   as actual_sum
FROM    baz

Results:

| TABLE_NAME |         DESCRIPTION | EXPECTED_SUM | ACTUAL_SUM |
|------------|---------------------|--------------|------------|
|        foo | mixed null/non-null |           21 |         21 |
|        bar |        all non-null |           21 |         21 |
|        baz |            all null |            0 |          0 |
2 of 4
84

Use IFNULL or COALESCE:

SELECT IFNULL(SUM(Column1), 0) AS total FROM...

SELECT COALESCE(SUM(Column1), 0) AS total FROM...

The difference between them is that IFNULL is a MySQL extension that takes two arguments, and COALESCE is a standard SQL function that can take one or more arguments. When you only have two arguments using IFNULL is slightly faster, though here the difference is insignificant since it is only called once.

Discussions

why am I having null in a sum in SQL?
Try this to ensure that the values are at least 0: COALESCE(column1,0) + COALESCE(column2,0) AS sum More on reddit.com
🌐 r/SQL
9
2
August 16, 2023
sql - mysql return default value 0 on SUM when there are no results - Stack Overflow
I am stuck on a query when I add the where clause. As expected I get no results so SUM has nothing to work with. I try to return a default value 0 for countSend and countPending when no rows are ma... More on stackoverflow.com
🌐 stackoverflow.com
sql - My Select SUM query returns null. It should return 0 - Stack Overflow
I needed to put COALESCE wrapper ... and on MySQL. 2016-12-28T14:38:56.037Z+00:00 ... COUNT(Field) will return 0 but SUM(Field) returns NULL if there are no matching rows. ... COUNT returns a different value 0 - meaning there are zero rows matching query , if there are 2 rows count will will return 2 , not the sum of the 2 rows 2013-06-11T15:51:21.65Z+00:00 ... @ScottSelby, sorry maybe I wasn't clear, I meant he may have been thinking of COUNT as returning ... More on stackoverflow.com
🌐 stackoverflow.com
August 5, 2019
mysql - How to get sum null values as zero while using group by - Stack Overflow
I have mysql query SELECT date, COALESCE(SUM(events),0) AS hotel_c FROM event_cohort_report WHERE date >= '2015-08-05' AND campaign='Pointific_Incent' AND country='IN' GROUP BY date when i ru... More on stackoverflow.com
🌐 stackoverflow.com
🌐
MySQL
bugs.mysql.com › bug.php
MySQL Bugs: #4346: SUM() Function returns 0 instead of NULL in a case
Description: The SUM() function should return NULL if the return set has no rows. I found a case where this does not work with 3.23.48. Following Statement: SELECT parent.parent_id, SUM( child.value ) AS result FROM child RIGHT JOIN parent ON child.id_parent = parent.parent_id GROUP BY ...
🌐
Reddit
reddit.com › r/sql › why am i having null in a sum in sql?
r/SQL on Reddit: why am I having null in a sum in SQL?
August 16, 2023 -

Hello everyone, I am new in data analytics and I am trying to sum 2 columns and create a new one with the total value, the thing is that I am having null values on the new column despite of having valid values on at least one of the summing fields, does anyone know what could be happening? Thanks in advance

🌐
TutorialsPoint
tutorialspoint.com › how-can-i-customize-the-output-of-mysql-sum-function-to-0-instead-of-null-when-there-are-no-matching-rows
How can I customize the output of MySQL SUM() function to 0 instead of NULL when there are no matching rows?
June 22, 2020 - As we know that the SUM() function ... of NULL. For this purpose, we can use the MySQL COALESCE() function which accepts two arguments and returns the second argument if the first argument is NULL, otherwise, it returns the first argument....
🌐
EDUCBA
educba.com › home › data science › data science tutorials › mysql tutorial › mysql sum()
MySQL sum() | Complete Guide to MySQL sum() with Query Examples
June 6, 2023 - When you use the SELECT statement with the SUM() function, which produces no rows, the MySQL SUM() function returns a NULL value instead of zero.
Address: Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 32005132 › how-to-get-sum-null-values-as-zero-while-using-group-by › 32006429
mysql - How to get sum null values as zero while using group by - Stack Overflow
SELECT date, COALESCE(SUM(events),0) AS hotel_c FROM event_cohort_report WHERE date >= '2015-08-05' AND campaign='Pointific_Incent' AND country='IN' GROUP BY date ... But i want for all date sum with zero if its not present in the table something like this. date hotel_c 2015-08-05 0 2015-08-06 0 2015-08-07 5411 2015-08-08 4602 2015-08-09 5151 2015-08-10 183 2015-08-11 1 ... The code that you are using is correct for getting value for null records.
🌐
TutorialsPoint
tutorialspoint.com › how-do-i-get-sum-function-in-mysql-to-return-0-if-no-values-are-found
How to select sum or 0 if no records exist in MySQL?
July 30, 2019 - +----------+ | SumOfAll | +----------+ ... you will get 0. The query is as follows. mysql> select COALESCE(sum(Counter), 0) AS SumOfAll from SumDemo where Words like '%End of MySQL%';...
🌐
Stack Overflow
stackoverflow.com › questions › 26123481 › null-value-to-zero-mysql
sum - Null value to zero mysql - Stack Overflow
September 30, 2014 - So plz give me any tips of MYSQL that convert empty to zero (0). ... Let x be the expression (e.g a field), which should be substituted with zero when it is null. Then you can use ... in place of x. The IF function gives its second argument if the first argument (the condition) is true, and the third argument if its first argument is false. ... Sign up to request clarification or add additional context in comments. ... Find the answer to your question by asking...
🌐
365 Data Science
365datascience.com › question › sum-for-columns-with-null-values
SQL Course and Certification – 365 Data Science
4 days ago - In this section, both will come together to show you how primary keys, foreign keys, and unique keys are applied in practice through MySQL Constraints. Once you have mastered these three, we will continue with other types of constraints that you will encounter daily in your work, such as the DEFAULT Constraint and the NOT NULL Constraint.
🌐
OneUptime
oneuptime.com › home › blog › how to use the sum() function in mysql
How to Use the SUM() Function in MySQL
March 31, 2026 - SUM() totals non-NULL numeric values in a column, ignoring NULLs by default. Use it with GROUP BY to get totals per group, HAVING to filter groups by their sum, and CASE WHEN inside SUM() for conditional totals.