Given a table of orders, can you write a SQL query to find the latest order for each customer?
💡 Model Answer
Sure. Assuming the table is named orders and has columns customer_id, order_id, order_date, you can use a window function to rank orders per customer by date and then pick the top one. For example:
SELECT customer_id, order_id, order_date
FROM (
SELECT customer_id,
order_id,
order_date,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC, order_id DESC) AS rnFROM orders
) t
WHERE rn = 1;
This returns the most recent order for each customer. If you only need the order_date, you can replace the SELECT list accordingly. The ROW_NUMBER() function assigns 1 to the latest order per customer, and the outer query filters to that row.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.
Get Assisting AI — Starts at ₹500