(this answer was added to provide shorter and more general examples of the question - without including all the details of a particular case in the original question).
There are two different "problems" here: the first - if there are no rows in the table or subquery, the second - if the query has NULL values.
For all versions I tested, postgres and mysql will ignore all NULL values ββwhen averaging and will return NULL if there is nothing to average. This usually makes sense, since NULL should be considered "unknown." If you want to override this, you can use coalescence (as suggested by Luke M).
$ create table foo (bar int); CREATE TABLE $ select avg(bar) from foo; avg ----- (1 row) $ select coalesce(avg(bar), 0) from foo; coalesce ---------- 0 (1 row) $ insert into foo values (3); INSERT 0 1 $ insert into foo values (9); INSERT 0 1 $ insert into foo values (NULL); INSERT 0 1 $ select coalesce(avg(bar), 0) from foo; coalesce -------------------- 6.0000000000000000 (1 row)
Of course, "from foo" can be replaced by "from (... any complex logic here ...) like foo"
Now, should the NULL row in the table be considered 0? Then you need to use the union inside the avg call.
$ select coalesce(avg(coalesce(bar, 0)), 0) from foo; coalesce
tobixen Jun 13 2018-12-12T00: 00Z
source share