Match Returned Units to Original Purchases Using First-In First-Out

Last updated: November 29, 2026

Quick Overview

Given purchases and returns of the same ASIN by the same customer, each with quantities, allocate returned units to the earliest purchases first and output how many units of each return came from each order.

Amazon
Data Manipulation (SQL/Python)
Data Engineer
Amazon
November 29, 2026
Data Engineer
Onsite
Data Manipulation (SQL/Python)
Hard

0

0

0 solved


Given purchases and returns of the same ASIN by the same customer, each with quantities, allocate returned units to the earliest purchases first and output how many units of each return came from each order.

A window function puzzle in the style of Amazon returns and finance reconciliation, where returns arrive without a reliable original order ID and must be matched to purchases to compute refunds and return rates. The interviewer checks cumulative quantity ranges and interval overlap logic in pure SQL.

What the Interviewer Expects
  • Compute running quantity totals for purchases and returns separately
  • Represent each row as a half-open range of unit numbers
  • Join on overlapping ranges within the same customer and ASIN
  • Compute matched quantity as the length of the overlap
  • Discuss returns that exceed purchases or precede them
Key Topics to Cover
running sums
interval overlap
FIFO allocation
window functions
reconciliation
How to Approach This
  1. Clarify the schema and expected output format before writing queries.
  2. Use CTEs (WITH clauses) to break complex queries into readable steps.
  3. Consider window functions (ROW_NUMBER, RANK, LAG, LEAD) for ranking and sequential analysis.
  4. Watch for NULLs, duplicates, and edge cases in JOINs and GROUP BY.
  5. For pandas, prefer vectorized operations over row-by-row iteration.
Possible Follow-up Questions
  • How would you enforce that a return can only match purchases made before it?
  • How would you switch to last-in first-out matching?
  • How would you compute the return rate per original order month from this output?
  • How would you do this in Python for a streaming feed?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice SQL Problems
Sample Answer
Clarify the Data

Tables:

  • purchases(customer_id, asin, order_id, order_ts, qty)
  • returns(customer_id, asin, return_id, return_ts, qty)

FIFO rule: number all purchased units of a customer and ASIN 1, 2, 3 in pur...

Approach

Running sums turn each row into a range of unit numbers. A purchase with qty = 3 and running total 5 covers units (2, 5]. A return with qty = 3 and running total 3 covers (0, 3]. Two ranges ov...


Submit Your Answer
Markdown supported