How can I calculate an average while ignoring missing values?
Quick answer
In SQLite, group your rows and select both AVG(rating) and COUNT(rating). AVG ignores NULL ratings, and COUNT(rating) counts the non-NULL ratings included in that average. [S1] For example: SELECT product, AVG(rating), COUNT(rating) FROM reviews GROUP BY product;. Groups with no non-NULL ratings have a NULL average and a count of 0. [S1]
The question, the details, the next step.
A practical checklist
Use
AVG(rating)for the average within each group.Use
COUNT(rating)to show the non-NULL ratings included.Add
COUNT(*)only if you also need the total rows per group.Check that rating values are numeric or NULL; SQLite treats nonnumeric text or BLOB values as 0 in
AVG. [S1]Decide how to present a group with no ratings, keeping clear that it has no observed average.
A few more useful answers
Does AVG ignore NULL values in each group?
Yes. SQLite’s AVG(X) averages non-NULL inputs within each group. If a group has no non-NULL inputs, it returns NULL. [S1]
What is the difference between COUNT(rating) and COUNT(*)?
COUNT(rating) counts non-NULL ratings; COUNT(*) counts all rows, including rows with NULL ratings. [S1]
Does SQLite ignore text values in an average?
Not necessarily. SQLite treats nonnumeric text or BLOB values as 0 in AVG, so use numeric ratings or NULL for missing values. [S1]
Sources
References used for this guide.
- [S1] SQLite AVG and COUNT behavior for NULL values sqlite.org · Checked
