Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Top-Selling Products by Month

MediumSQL · PostgreSQL00:00
Practice interviewer
In session
5 left
00:00

Your question is Top-Selling Products by Month. Start with the requirements and the three tables on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Fashion Nova wants a monthly view of its highest-revenue products. Write a PostgreSQL query that returns the top two products by revenue for every calendar month represented in the order data.

Requirements

  1. Include only orders whose status is completed.
  2. Calculate product revenue as quantity * unit_price, grouped by calendar month and product.
  3. Use a window function to rank products within each month and return ranks 1 and 2, including ties.
  4. Sort the final output by month ascending, revenue descending, and product ID ascending.

Schema

products
ColumnTypeDescription
product_idPKINTUnique product identifier
skuVARCHAR(30)Fashion Nova stock keeping unit
product_nameVARCHAR(100)Product display name
orders
ColumnTypeDescription
order_idPKINTUnique order identifier
ordered_atTIMESTAMPTimestamp when the order was placed
statusVARCHAR(20)Order lifecycle status
order_items
ColumnTypeDescription
line_idPKINTUnique order-line identifier
order_idINTReferenced order
product_idINTReferenced product
quantityINTNumber of units in the line item
unit_priceNUMERIC(10,2)Selling price per unit
Tablesordersorder_itemsproducts
Your solutionPostgreSQL
You need to log in / sign up to run or submit.
Run a query to see results