← Back to SQL, page 20

sql-0399 · Easy fresher

Design tables for product reviews with star ratings and a fast average rating on product pages.

Store reviews with product, customer, rating (CHECK between 1 and 5), text and status, with a unique (product_id, customer_id) for one review per customer. Keep rating_count and rating_sum on the product (or a summary table), updated in the same transaction as review changes, so pages read the average without scanning reviews.

Full answer
text
reviews(id, product_id, customer_id, rating INT CHECK (rating BETWEEN 1 AND 5),
        body, status CHECK IN ('pending','published','rejected'), created_at,
        UNIQUE (product_id, customer_id))
product_rating_summary(product_id PK, rating_count, rating_sum)

Average = rating_sum * 1.0 / NULLIF(rating_count, 0). Storing sum and count rather than the average itself lets each change adjust the totals exactly.

Rules to decide:

  • Only published reviews count; moderation changes must update the summary.
  • Editing a rating subtracts the old value and adds the new one.
  • A periodic job recomputes summaries from reviews to correct any drift.
  • For sorting by quality, a Bayesian average (pulling products with few reviews towards the site mean) avoids a single 5-star review topping the list.

Index reviews(product_id, status, created_at DESC) for the review list on the product page.

Key points

  • Rating CHECK 1 to 5
  • One review per customer per product
  • Cache sum and count, not the average
  • Recompute periodically
  • Bayesian average for ranking

Common mistakes

  • Computing AVG over all reviews on every page view
  • Counting unmoderated reviews

Follow-ups

  • How would you show the rating distribution?
  • How would you detect fake reviews?

Tips

  • Explain sum and count over a stored average