Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

SQL Top 3 Products by Category

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

Your question is SQL Top 3 Products by Category. 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

Nestlé USA marketing analysts need a category-level view of product performance across brands such as NESCAFÉ, KITKAT, and Stouffer’s. Write a PostgreSQL query that returns the three highest-selling products within every category.

Requirements

  1. Join the category, product, and sales tables.
  2. Calculate total sales for each product using sales_amount.
  3. Rank products independently within each category, with the highest total sales ranked first.
  4. Return only ranks 1 through 3, ordered by category and rank. Treat NULL sales amounts as zero when calculating totals.

Use ROW_NUMBER() so ties are resolved deterministically by the smaller product_id.

Schema

categories
ColumnTypeDescription
category_idPKINTEGERUnique product category identifier
category_nameVARCHAR(100)Product category name
products
ColumnTypeDescription
product_idPKINTEGERUnique product identifier
product_nameVARCHAR(150)Nestlé USA product name
category_idINTEGERReferences categories.category_id
sales
ColumnTypeDescription
sale_idPKINTEGERUnique sales record identifier
product_idINTEGERReferences products.product_id
sales_amountNUMERIC(12,2)Revenue associated with the sales record
Tablescategoriesproductssales
Your solutionPostgreSQL
You need to log in / sign up to run or submit.
Run a query to see results