Someone e-mailed me a question directly (name and address withheld on request). The question was a good one, so I thought I'd address it with a post here:
"Why would you assume NULL values are zeroes [by using COALESCE(column, 0)] in your AVG() function calls? It seems like that would throw your answer even further off!"
That's an excellent question! On the face of it, it doesn't appear to make much sense for normal averaging. But bear with me as I walk through this scenario:
You have a room with 20 football players in it, and you have to calculate the average weight for the room. If 10 players refuse to give their weight (i.e., NULL), how do you estimate the average?
Using AVG(weight) and eliminating NULLs gives us an average at a point in time when we only have half the data. This is standard practice, and it is 'precise', but it is not 'accurate'. The fact that it is not accurate should be noted on reports generated using this data. After all, this average accounts for only 50% of the players in the room; and our final result, once we get the remaining players' weights could be heavily weighted (no pun intended) in one direction or the other. I.e., if our average is 150 pounds with 10 players responding, it could very well jump to 250 or higher by the time we get everyone's weights included in the final calculation.
Can we be more accurate than this? The answer is yes, but we will become less 'precise' in the process.
Let's say that we have a tid-bit of information about the football players in the room. We are told in advance that nobody is over 300 pounds, and we determine (obviously) that nobody is less than 0 pounds. Since this is a football team, management wants all the players to be bulky; therefore, the greater the weight, the better. These are our best-case/worst-case scenarios. Using these two numbers, with COALESCE(), we can come up with best-case/worst-case scenario averages:
SELECT AVG(COALESCE(weight, 300)) AS BestCase
SELECT AVG(COALESCE(weight, 0)) AS WorstCase
This will give us a range that we know our final average will fall between. We can make our answer more precise if we can narrow our limits (i.e., no one weighs less than 100 pounds).
We actually use these type of range calculations all the time without even thinking about them. When someone asks how much something costs ("$5 to $10"), how much profit the company will make this year ("between $1.6 mil. and $1.8 mil."), or what time will we arrive ("between 5:00 and 5:30").
So to answer the question, AVG(COALESCE()) is useful when trying to determine best-case average, worst-case average, or when determining a range for our averages.