Given a table named Orders with columns OrderID, CustomerID, OrderDate, ProductID, and Amount, write a SQL query to retrieve the latest record for each customer.
1Times asked
Aug 2026Last seen
Aug 2026First seen
💡 Model Answer
You can use a window function to rank orders per customer by date and then filter for the most recent one:
sql
SELECT OrderID, CustomerID, OrderDate, ProductID, Amount
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY CustomerID ORDER BY OrderDate DESC) AS rn
FROM Orders
) AS sub
WHERE rn = 1;This query partitions the data by CustomerID, orders each partition by OrderDate descending, assigns a row number, and then selects only the first row (the latest order) for each customer. If you need the most recent order per customer across all columns, this approach works for any SQL dialect that supports window functions.
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