HardSQL challenge #193CTEMulti-JOINCOALESCELEFT JOINAggregation

Build a Product Performance Report with Two CTEs

For the top 20 active products by revenue, show units sold, revenue, average review, review count and margin.

The challenge runs on the SQLabHub practice database (SQLite) and uses the products, order_items and reviews tables. You can solve it in the browser, with nothing to install.

Solve This SQL Challenge

The task

For each active product: units sold, revenue, average review rating, review count and profit margin %. Aggregate sales and reviews separately before joining them to products.

A correct answer returns 20 rows with 8 columns: name, category, price, units_sold, revenue, avg_review, review_count, margin_pct.

Tables used in this challenge

products 120 rows

id INTEGER (PK) · name TEXT · category TEXT · price REAL · cost REAL · stock INTEGER · sku TEXT · status TEXT · rating REAL · review_count INTEGER

First 3 rows of the products table
idnamecategorypricecoststockskustatusratingreview_count
1Play Kitchen DeluxeToys1786.38589.51257SKU-000001active457
2Micro-Cut Paper Shredder 8-SheetOffice Supplies907.93281.46131SKU-000002active2.5447
34K Dual Dash CameraAutomotive568.89204.8176SKU-000003active4.129

order_items 496 rows

id INTEGER (PK) · order_id INTEGER · product_id INTEGER · quantity INTEGER · unit_price REAL · subtotal REAL

First 3 rows of the order_items table
idorder_idproduct_idquantityunit_pricesubtotal
11765192.21961.05
21823107.1321.3
316515.395.39

reviews 180 rows

id INTEGER (PK) · product_id INTEGER · user_id INTEGER · rating INTEGER · comment TEXT · reviewed_at TEXT · helpful_votes INTEGER

First 3 rows of the reviews table
idproduct_iduser_idratingcommentreviewed_athelpful_votes
123455Works perfectly. Very happy with this purchase.2022-09-0240
2101685Excellent build quality. Will buy again!2023-01-0596
340391Would give 6 stars if I could!2023-05-1517

The first rows of each table are shown. See how all the tables relate on the database schema page.

Expected output

Expected output of the challenge
namecategorypriceunits_soldrevenueavg_reviewreview_countmargin_pct
Merino Wool SweaterClothing1473.96308995.831.5251
LEGO Creator Set 742pcsToys397378530.61NULL067
Leather Steering Wheel CoverAutomotive1727.7257519.96NULL047
Ergonomic Desk Mat XLOffice Supplies1233.19337066.042.5269
Ergonomic Desk Mat XLOffice Supplies1839.35246944.33NULL061

First 5 of 20 rows. This is the output of the model solution on the practice database.

What you practise

  • Filtering rows with a WHERE condition
  • Summarising many rows into one value with COUNT, SUM, AVG, MIN or MAX
  • Grouping rows with GROUP BY to get one result row per group
  • Keeping every row of the left table with LEFT JOIN, matched or not
  • Naming an intermediate result with a WITH clause and reading from it
  • Replacing NULL with a default using COALESCE
  • Sorting the result with ORDER BY
  • Returning only the first rows with LIMIT

Hint and approach

Try the challenge first. Open these only when you need them.

Show the hint

Summarise order_items and reviews in two CTEs, then LEFT JOIN both to products. Joining the raw tables together would multiply the sales by the number of reviews.

Show the step-by-step approach

How the model solution is built, in the order the database evaluates it:

  1. Define a common table expression named sales:
    1. Read from the order_items table.
    2. Group the rows by product_id, so the result has one row for each value.
    3. For each group, compute SUM(quantity) and SUM(subtotal).
  2. Define a common table expression named ratings:
    1. Read from the reviews table.
    2. Group the rows by product_id, so the result has one row for each value.
    3. For each group, compute AVG(rating) and COUNT(*).
  3. Read from the products table.
  4. LEFT JOIN sales on sales.product_id = products.id. Rows from the left side that have no match are kept, with NULL in the joined columns.
  5. LEFT JOIN ratings on ratings.product_id = products.id. Rows from the left side that have no match are kept, with NULL in the joined columns.
  6. Filter in WHERE: keep the rows where products.status equals 'active'.
  7. ROUND() trims the calculated figures to a fixed number of decimals.
  8. COALESCE(x, 0) replaces a NULL result with 0.
  9. Sort the result by revenue descending.
  10. Keep only the first 20 rows with LIMIT.

Model solution

Checking your session…

What to watch for

One CTE summarises sales and another summarises reviews, each to one row per product, and only then are they joined to products. Joining order_items and reviews directly would repeat every order line once per review and overstate units and revenue. The margin uses 100.0 so the division is not truncated.

  • CTE (WITH). A CTE exists only for the single statement it is attached to. It is not a temporary table and cannot be reused by the next query.
  • LEFT JOIN. A WHERE condition on the right-hand table removes the unmatched rows and turns the LEFT JOIN back into an inner join. Conditions on that table go in the ON clause.
  • GROUP BY. Every selected column must either be in GROUP BY or sit inside an aggregate. SQLite accepts other columns and returns an arbitrary value for them; most databases raise an error.
Solve This SQL Challenge

Keep learning