Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: AVG with NULL Values

As far as I understood, the AVG() function ignores NULL Values.

So AVG(4,4,4,4,4,NULL) --> 4

In my case I don't want this to happen.

I need a solution like that: AVG(4,4,4,4,4,NULL) --> 3,33

without replacing the NULL values directly in the table itself.

Is there any way to do this?

like image 823
user3364656 Avatar asked Mar 06 '14 09:03

user3364656


2 Answers

Use coalesce() to return the real value of zero for null columns:

select avg(coalesce(some_column, 0))
from ...
like image 130
Bohemian Avatar answered Oct 20 '22 17:10

Bohemian


You are correct about the behavior of AVG - use COALESCE to convert the NULLs to 0 in the aggregate.

See this answer in "Why SUM(null) is not 0 in Oracle?"

If you are looking for a rationale for this behaviour, then it is to be found in the ANSI SQL standards which dictate that aggregate operators ignore NULL values.

The relevant code is then, simply:

Avg(Coalesce(col,0))
like image 36
user2864740 Avatar answered Oct 20 '22 18:10

user2864740