SQL interview questions

SQL Advanced level Question 2

Question2: Find the product with the highest average rating, and return the product ID, average rating, and the number of reviews for that product. If there are multiple products with the highest average rating, return all of them.

review_idproduct_idcustomer_idreview _textratingreview _date
11011Great product, really loved it!52025-01-15 12:00:00
21022Not as expected, quality could be better.32025-01-15 12:05:00
31013Excellent value for money. Highly recommended!52025-01-15 12:10:00
41034The item arrived broken. Disappointed.12025-01-15 12:15:00
51025Okay product, works as described.42025-01-15 12:20:00
61016Fantastic quality and fast shipping!52025-01-15 12:25:00
71047Very poor design, uncomfortable to use.22025-01-15 12:30:00
81038Good product but needs improvement.32025-01-15 12:35:00
91059Absolutely terrible, do not buy!12025-01-15 12:40:00
1010110Solid product, works great.42025-01-15 12:45:00
WITH product_avg_ratings AS (
    SELECT 
        product_id, 
        AVG(rating) AS avg_rating,
        COUNT(review_id) AS review_count
    FROM product_reviews
    GROUP BY product_id
),
max_avg_rating AS (
    SELECT 
        MAX(avg_rating) AS highest_avg_rating
    FROM product_avg_ratings
)
SELECT 
    p.product_id,
    p.avg_rating,
    p.review_count
FROM product_avg_ratings p
JOIN max_avg_rating m ON p.avg_rating = m.highest_avg_rating
ORDER BY p.product_id;
Explanation:
  1. CTE product_avg_ratings: This Common Table Expression calculates the average rating (avg_rating) and the total number of reviews (review_count) for each product.
  2. CTE max_avg_rating: This CTE finds the highest average rating across all products.
  3. Final SELECT Query: It joins the two CTEs to fetch the product_id, avg_rating, and review_count for the products that have the highest average rating. The results are ordered by product_id to make it more readable.
Sample Output:
If, for example, products 101 and 102 have the highest average ratings, the result could look like this:
product_idavg_ratingreview_count
1014.85
1024.02
Comment form