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.
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
| id | name | category | price | cost | stock | sku | status | rating | review_count |
|---|---|---|---|---|---|---|---|---|---|
order_items 496 rows
id INTEGER (PK) · order_id INTEGER · product_id INTEGER · quantity INTEGER · unit_price REAL · subtotal REAL
| id | order_id | product_id | quantity | unit_price | subtotal |
|---|---|---|---|---|---|
reviews 180 rows
id INTEGER (PK) · product_id INTEGER · user_id INTEGER · rating INTEGER · comment TEXT · reviewed_at TEXT · helpful_votes INTEGER
| id | product_id | user_id | rating | comment | reviewed_at | helpful_votes |
|---|---|---|---|---|---|---|
The first rows of each table are shown. See how all the tables relate on the database schema page.
Expected output
| name | category | price | units_sold | revenue | avg_review | review_count | margin_pct |
|---|---|---|---|---|---|---|---|
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:
- Define a common table expression named
sales:- Read from the
order_itemstable. - Group the rows by
product_id, so the result has one row for each value. - For each group, compute
SUM(quantity)andSUM(subtotal).
- Read from the
- Define a common table expression named
ratings:- Read from the
reviewstable. - Group the rows by
product_id, so the result has one row for each value. - For each group, compute
AVG(rating)andCOUNT(*).
- Read from the
- Read from the
productstable. - LEFT JOIN
salesonsales.product_id=products.id. Rows from the left side that have no match are kept, with NULL in the joined columns. - LEFT JOIN
ratingsonratings.product_id=products.id. Rows from the left side that have no match are kept, with NULL in the joined columns. - Filter in
WHERE: keep the rows whereproducts.statusequals 'active'. ROUND()trims the calculated figures to a fixed number of decimals.COALESCE(x, 0)replaces a NULL result with 0.- Sort the result by
revenuedescending. - 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.
Related SQL challenges
- Segment Customers by Recency, Frequency and Monetary Value (RFM)Similar levelHard
- Find the Longest Streak of Rising Daily RevenueSimilar levelHard
- Show Review Count and Units Sold per ProductEasierMedium
- Find the Top 15 Customers by Lifetime RevenueEasierMedium
- Build a Monthly Revenue Report Excluding Cancelled OrdersEasierMedium
Keep learning
- Lesson: CTEs (WITH Clause)
- Lesson: LEFT JOIN
- Lesson: GROUP BY
- Lesson: COALESCE
- All SQL practice challenges, by difficulty and topic
- SQL interview questions with answers
- SQL Playground: run any query on the same database