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