12. The average rating where NULL is not zero

SQLEasyNULL trap

aggregation · count · avg · nulls · coalesce

How the Colab notebook works

The notebook has the data, an answer cell and a check() function. You need a Google account; nothing is installed on your machine. Free Colab runs only two or three notebooks at a time, so end the session of a finished problem (Runtime > Disconnect and delete runtime) before opening the next one. "Mark as solved" is remembered in this browser only.

The situation

Customers can leave a written review without giving a star rating. The product page shows three numbers per product: how many reviews it has, how many of those carry a rating, and the average rating.

A previous version of this report showed products with good reviews at 2.9 stars. Somebody had "cleaned" the missing ratings first.

Input tables

reviews

One row per review.

Column Type Description
review_id BIGINT Unique per review.
product_id BIGINT The product being reviewed.
rating INT 1 to 5 stars. NULL means the customer wrote a review without rating the product.

Requirement

Return one row per product.

  • total_reviews is the number of reviews of the product, rated or not.
  • rated_reviews is the number of reviews that have a rating.
  • avg_rating is the average of the ratings that exist. A review without a rating does not count as zero stars; it does not count at all.
  • A product with no rated reviews has rated_reviews = 0 and avg_rating = NULL.
  • Do not round avg_rating.

Expected output

One row per product.

Column Type Description
product_id BIGINT
total_reviews BIGINT All reviews.
rated_reviews BIGINT Reviews with a rating.
avg_rating DOUBLE Average rating. NULL if no review is rated.

Solve it in the browser

This editor runs DuckDB inside your browser. Nothing is installed and nothing is sent to a server. DuckDB's SQL is close to Spark SQL but not identical. The Colab notebook runs real Spark.

query.sql DuckDB, in your browser
Ctrl + Enter runs the query

Your result appears here. Your draft is kept in this browser.

Explanation

Show explanationGives the answer away. Try the problem first.

The approach

SELECT
    product_id,
    COUNT(*) AS total_reviews,
    COUNT(rating) AS rated_reviews,
    AVG(rating) AS avg_rating
FROM reviews
GROUP BY product_id

The query is four lines. The point is knowing exactly what each aggregate does with NULL:

  • COUNT(*) counts rows. It does not look at any column.
  • COUNT(rating) counts the rows where rating is not NULL.
  • AVG(rating) is the sum of the non-NULL ratings divided by the number of non-NULL ratings. NULL rows are not part of the sum and not part of the count.
  • AVG over no values at all is NULL, not 0.

So the default behaviour is already what the requirement asks for. Every wrong answer to this problem comes from "handling" the NULLs when they needed no handling.

The table has 203 reviews of 30 products. 49 reviews carry no rating.

Common wrong answers

AVG(COALESCE(rating, 0)). This turns "no rating" into "zero stars" and then averages it in. Across the whole table the average rating is 3.49; with the NULLs replaced by 0 it becomes 2.65. This is how a product with good reviews ends up at 2.9 stars. NULL means unknown. Replacing it with 0 states something that nobody said.

SUM(rating) / COUNT(*). The same mistake by another route. SUM skips the NULLs but COUNT(*) does not, so the unrated reviews are in the denominator and not in the numerator.

COUNT(*) for rated_reviews. Reports every review as rated. If you see two count columns in a report that are always equal, check whether one of them was meant to be COUNT(column).

Filtering WHERE rating IS NOT NULL first. The average is now right, but total_reviews only counts rated reviews, and the result has 28 rows instead of 30. Products 828 and 829 have only unrated reviews, so the filter removes every row they have and they vanish from the report.

COALESCE(AVG(rating), 0). Shows products 828 and 829 with an average of 0. A product nobody has rated is not a zero-star product. Leave it NULL and let the page show "not rated yet".

A note on PySpark

F.count("*") and F.count("rating") behave exactly like the SQL versions, and F.avg ignores NULLs too. df.fillna(0) before aggregating is the DataFrame version of the COALESCE mistake, and it is more dangerous because it changes every numeric column at once.

Edge cases in the data

Case Where What it catches
Reviews without a rating 49 of 203 rows Treating NULL as 0.
Product with several reviews, none rated 829 WHERE rating IS NOT NULL drops it; COALESCE(AVG, 0) shows 0.
Product with a single unrated review 828 The same, with one row.
Product with a single rated review 830 An average of one value.