Top Product Categories by Sales

An easy SQL interview practice problem on DataDriven. Write the query and run it against a real database, with instant feedback.

Domain
SQL
Difficulty
easy
Seniority
L3
Asked in
Audible

Problem

Our category revenue dashboard stopped matching finance, so we want to rebuild it straight from the transactions and products tables. Total the transaction amounts for each product category, from highest revenue to lowest.

The highest-grossing categories.

Tables

products

Columns: product_id INTEGER, product_name TEXT, category TEXT, price REAL, rating REAL, in_stock INTEGER

products: 10 of 200 rows
product_idproduct_namecategorypriceratingin_stock
1001Basic Device 1XBooks17.522.71
1050Deluxe Bundle 2XClothing25.054.41
1099Pro Unit 3XHome & Kitchen32.582.11
1148Ultra Tool 4XCollectibles40.113.81
1197Essential Set 5XToys47.641.51
1246Classic System 6XBeauty03.21
1295Smart Gadget 7XAutomotive62.74.90
1344Eco Kit 8XGarden70.232.61
1393Turbo Pack 9XMusic77.764.30
1442Premium Widget 10XElectronics85.2921

transactions

Columns: transaction_id INTEGER, user_id INTEGER, product_id INTEGER, quantity INTEGER, total_amount REAL, transaction_date TEXT

transactions: 10 of 200 rows
transaction_iduser_idproduct_idquantitytotal_amounttransaction_date
10671971001223.462026-02-02
11342941050336.932026-03-03
12013911099450.42026-04-04
12684881148563.872026-05-05
13355851197002026-06-06
14026821246290.812026-07-07
146977912953104.282026-08-08
153687613444117.752026-09-09
160397313935-452026-01-10
1670107014421144.692026-02-11

Expected output

First 5 of 11 rows
categorytotal_revenue
Electronics15016.8
Books12501.39
Clothing12487.92
Home & Kitchen12222
Toys12090.78

Worked solution and explanation

What this is really asking

category lives on products (20k rows), revenue lives on transactions (80M rows). Join on product_id, SUM total_amount per category, ORDER BY revenue DESC. The join direction matters at this row count.


Break down the requirements

Step 1: Get category onto each transaction

INNER JOIN transactions to products on product_id. A transaction with no matching product is corruption, not a category.

Step 2: Aggregate by category

SUM(t.total_amount) grouped by p.category. Use total_amount directly; promotions and refunds already settled into it.

Step 3: Sort descending

ORDER BY total_revenue DESC ranks all categories. No LIMIT.


REVENUE BY CATEGORY
SELECT
  p.category,
  SUM(t.total_amount) AS total_revenue
FROM products p
INNER JOIN transactions t
  ON p.product_id = t.product_id
GROUP BY p.category
ORDER BY total_revenue DESC

COMMON FOLLOW-UP QUESTIONS

Common follow-up questions