Given the following table of customer events, write a SQL query to find the most recent status for each customer.
💡 Model Answer
To return the most recent status for each customer, you can use a window function that assigns a row number to each event per customer ordered by event_time descending. Then filter for row_number = 1. Example:
SELECT customer_id, event_time, status
FROM (
SELECT
customer_id,
event_time,
status,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY event_time DESC) AS rn
FROM events) t
WHERE rn = 1;
This query partitions the data by customer_id, orders each partition by event_time descending, and numbers the rows. The outer query keeps only the first row per customer, which is the latest event. Complexity is dominated by the sort, O(n log n). If the table is large, create an index on (customer_id, event_time) to speed the partitioning. An alternative approach is to use a GROUP BY to find the maximum event_time per customer and then join back to the original table to retrieve the status. That approach uses a single aggregation and a join, also O(n).
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