API Design interview question · Most asked

Write a SQL query that returns each customer's three most recent orders.

Hands-on Asked in Backend Engineer · Full Stack Engineer · Native AI Engineer · Forward Deployed Engineer (FDE) · QA Engineer / SDET · Tech Lead interviews

Members can save this page, take notes and track progress. See membership · Sign in

Summary

Rank each customer's orders by date with a window function, then keep ranks 1 to 3. ROW_NUMBER() gives exactly three per customer; RANK() would include ties.

Longer Answer

An index on (customer_id, ordered_at DESC) makes this efficient. In PostgreSQL, a LATERAL join with LIMIT 3 can be faster when you only need a few customers, because it can use that index directly per customer.

Example

SELECT customer_id, order_id, ordered_at, total
FROM (
  SELECT o.*,
         ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY ordered_at DESC) AS rn
  FROM orders o
) ranked
WHERE rn <= 3
ORDER BY customer_id, ordered_at DESC;

-- PostgreSQL alternative using the index per customer
SELECT c.id AS customer_id, recent.*
FROM customers c
CROSS JOIN LATERAL (
  SELECT order_id, ordered_at, total FROM orders
  WHERE customer_id = c.id ORDER BY ordered_at DESC LIMIT 3
) recent;

Key Points

  • Window function per customer.
  • ROW_NUMBER for exactly N; RANK keeps ties.
  • Composite index on (customer_id, ordered_at DESC).
  • LATERAL + LIMIT as an alternative.

Explanation

What interviewers look for

Fluent use of window functions and indexing awareness.

More API Design questions

← All API Design questions

Last reviewed · By the ByteCamel team · How we write content

Was this page helpful?

Report a mistake