21

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?

peterh
  • 11,875
  • 18
  • 85
  • 108
user3364656
  • 279
  • 2
  • 4
  • 9

5 Answers5

28

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

select avg(coalesce(some_column, 0))
from ...
Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • 1
    Lots of variants to this COALESCE syntax. I like ISNULL() functions best (makes more sense linguistically). More info: https://www.w3schools.com/sql/sql_isnull.asp – Dave Skender Dec 03 '19 at 18:23
4

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))
Community
  • 1
  • 1
user2864740
  • 60,010
  • 15
  • 145
  • 220
0

You can use coalesce or nvl also. Since coalesce examples are already given above, here is an example of nvl

Avg(Nvl(Column_Name),0)

Coalesce, Nvl, Nvl2 functions are handy in such cases of handling null values. You should look up some examples and documentation on these.

0

NVL, NVL2, or COALESCE could be used to solve this issue.

like this select avg(4,4,4,4, nvl(null, 0 )) from dual;

NatiCog
  • 49
  • 3
0

Another possibility is to calculate average using aggregate functions SUM with COUNT

SELECT SUM(column_with_value) / COUNT(primary_column) FROM ...
J. Gobet
  • 179
  • 1
  • 5