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
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
- What makes an API RESTful, and what are good REST design practices?
- Compare offset pagination and cursor (keyset) pagination.
- Write an Express or FastAPI endpoint that creates an order idempotently.
- An API endpoint that was fast is now taking seconds under load. Walk through your investigation.
- Which HTTP methods are safe and idempotent, and why does it matter?
- Which HTTP status codes should an API use, and when?
- How do idempotency keys work for POST requests?
- How should you version an API?