I need to perform an avg on a column, but I know that most of the values in that column will be zero. Out of all possible rows, only two will probably have positive values. How can I tell mySQL to ignore the zeros and only average the actual values?
Asked
Active
Viewed 2.4k times
4 Answers
99
Assuming that you might want to not totally exclude such rows (perhaps they have values in other columns you want to aggregate)
SELECT AVG(NULLIF(field ,0))
from table

Martin Smith
- 438,706
- 87
- 741
- 845
-
Thanks, this will probably be the best option because yes, I do have values in the other columnns! – Oranges13 Mar 17 '11 at 18:18
-
2this works great -- especially when you have more than 1 aggregate function in your query – Avishai Jan 01 '13 at 23:42
-
Thanks! I was struggling with this one for a couple of minutes. – CJL89 May 28 '21 at 19:16
5
You could probably control that via the WHERE clause:
select avg( field ) from table where field > 0

Mark Wilkins
- 40,729
- 5
- 57
- 110
-
Only if the rows where field is greater than zero are the ones I'm worried about. Unfortunately in this case, there are 3 other columns I need to check where that may not be the case. – Oranges13 Mar 17 '11 at 19:53
1
select avg(your_column)
from your_table
where your_column != 0

Ike Walker
- 64,401
- 14
- 110
- 109
-
That works, except there are other fields I wish to pull at the same time as one big average. – Oranges13 Mar 17 '11 at 19:52
0
You can convert zeros to NULL
, then AVG()
function will work only with not NULL
values.
UPDATE table SET column = NULL WHERE column='0';
SELECT AVG(column) FROM table;

Thomas Berger
- 1,860
- 13
- 26

Barvajz
- 25
- 1
-
5Yeesh. Changing existing data to make a `SELECT` work? I think I'm gonna puke... – Matthew Clark Dec 23 '14 at 20:39