Dataford
Interview QuestionsInterview GuidesExperiencesCoaching
New
Pricing
Get started
Dataford
Popular roles
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Browse
Browse All RolesEvery role hub, from analyst to MLBrowse All CompaniesCompany-specific interview loopsAll Interview GuidesThe full guide library
Top questions by role
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Top questions by skill
SQLPythonStatisticsMachine LearningA/B TestingSystem DesignGenerative AIProduct SenseMetricsBehavioral
Browse all questions →Try a mock interview
Experiences
Practice
Mock InterviewsTimed interview simulations with feedbackCoaching1:1 coaching with people at your target companiesSuccess PathYour 6-week structured planModulesCurated lessons by topicWebinarsTalks from ex-Big Tech data leadsPlaygroundA free-form scratch editor
Learn
BlogInterview strategy and career adviceTech Job Market ReportHiring trends across data and AI rolesFor UniversitiesDataford for career centersAbout DatafordWho we are and how we build
Pricing
Build my plan
SQL Top 3 Products by Category
00:00
5 left

SQL Top 3 Products by Category

EasySQL · PostgreSQL

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
Interviewer

Your question is SQL Top 3 Products by Category. Start with the requirements and the three tables in the Question tab.

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.
CodePostgreSQL
Sign up free to run your codeLog inLn 1
Run your query to see results here.