Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started
Top 3 Items Per Region Query
00:00
5 left

Top 3 Items Per Region Query

MediumSQL · PostgreSQL

Problem

The Apexon Data & AI platform tracks high-volume user transactions across regions. Write a PostgreSQL query that identifies the three most purchased items in each region during the last 30 days, using completed transactions only.

Output

  1. Return one row per item included in the regional top three, with columns region, item_id, item_name, purchased_units, and region_rank.
  2. Exclude transactions outside the inclusive 30-day interval ending on 2026-08-29, transactions that are not completed, transactions with non-positive or NULL quantities, and users whose region is NULL.
  3. Aggregate purchased units by region and item, rank items independently within each region, and return no more than three rows per region.
  4. Break quantity ties by ascending item_id, and order the final result by region and region_rank.

Schema

transactions
ColumnTypeDescription
transaction_idPKBIGINTUnique transaction identifier
user_idBIGINTReferences users.user_id
item_idBIGINTReferences items.item_id
quantityINTEGERNumber of units in the transaction
occurred_atTIMESTAMPTimestamp when the transaction occurred
statusVARCHAR(20)Transaction processing status
users
ColumnTypeDescription
user_idPKBIGINTUnique user identifier
regionVARCHAR(40)Geographic region assigned to the user
items
ColumnTypeDescription
item_idPKBIGINTUnique item identifier
item_nameVARCHAR(100)Display name of the purchased item
Tablestransactionsusersitems
Interviewer

Your question is Top 3 Items Per Region Query. 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
You need to log in / sign up to run or submit.Ln 1
Run your query to see results here.