Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Top 5 Categories by Month

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

Your question is Top 5 Categories by Month. Start with the requirements and the four 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

Citizant's federal sales reporting dataset contains orders, line items, products, and product categories. Write a PostgreSQL query that identifies the five highest-selling categories within each calendar month.

Requirements

  1. Include only orders whose status is completed.
  2. Calculate sales as quantity * unit_price at the line-item level, then aggregate by month and category.
  3. Rank categories independently within each month using a window function.
  4. Return no more than five categories per month, ordered by month and descending sales rank.
  5. Exclude products that do not map to a category, and handle nullable quantities correctly.

Schema

sales_orders
ColumnTypeDescription
order_idPKINTUnique order identifier
order_dateDATEDate the order was placed
statusVARCHAR(20)Order processing status
order_items
ColumnTypeDescription
order_item_idPKINTUnique line-item identifier
order_idINTReferences sales_orders.order_id
product_idINTReferences products.product_id
quantityINTNumber of units sold
unit_priceNUMERIC(10,2)Price charged per unit
products
ColumnTypeDescription
product_idPKINTUnique product identifier
product_nameVARCHAR(100)Product display name
category_idINTReferences categories.category_id
categories
ColumnTypeDescription
category_idPKINTUnique category identifier
category_nameVARCHAR(100)Product category name
Tablessales_ordersorder_itemsproductscategories
Your solutionPostgreSQL
You need to log in / sign up to run or submit.
Run a query to see results