Interview Questions/SQL/Product Sales Summary by Category

Product Sales Summary by Category

Preview mode. Log in to edit, run, submit, and save progress.

Medium

Description

You are given two tables: Products and Orders. Each product belongs to a category and has a price. Each order references a product and includes a quantity. Write a SQL query to find for each product category: the total number of orders, the total units sold, and the total revenue (quantity × price). Categories with no orders should still appear with 0 order_count, NULL total_units, and NULL total_revenue. Return the result ordered by total_revenue descending (NULLs last). Table: Products

Column NameTypeDescription
idINTPrimary key
nameVARCHARProduct name
categoryVARCHARProduct category
priceDECIMALUnit price

Table: Orders

Column NameTypeDescription
idINTPrimary key
product_idINTReferences Products.id
quantityINTUnits ordered
order_dateDATEDate of the order

Database Schema (Inferred)

Products

Column NameExample Value
id1
nameLaptop
categoryElectronics
price1200

Orders

Column NameExample Value
id1
product_id1
quantity2
order_date2023-01-10

Example

Products

idnamecategoryprice
1LaptopElectronics1200
2PhoneElectronics800
3DeskFurniture400
4ChairFurniture250
5NotebookStationery5

Orders

idproduct_idquantityorder_date
1122023-01-10
2252023-01-15
3312023-01-20
4432023-02-05
551002023-02-10
6112023-02-15

Output

categoryorder_counttotal_unitstotal_revenue
Electronics387600
Furniture241150
Stationery1100500

Explanation:

Group orders by category via a join on Products. SUM(quantity * price) gives revenue. ORDER BY total_revenue DESC.

Approach hint

Start with a simple approach, explain the trade-off, then move toward a cleaner or more scalable solution.

Common mistake

Skipping assumptions, edge cases, or trade-offs can make an otherwise good answer feel incomplete.

SQL Editor
Loading...

Products

idnamecategoryprice
1LaptopElectronics1200
2PhoneElectronics800
3DeskFurniture400
4ChairFurniture250
5NotebookStationery5

Orders

idproduct_idquantityorder_date
1122023-01-10
2252023-01-15
3312023-01-20
4432023-02-05
551002023-02-10
6112023-02-15

Output

categoryorder_counttotal_unitstotal_revenue
Electronics387600
Furniture241150
Stationery1100500