How do you get one latest event per user?
Question
Return one event per user. Take the newest recorded_at. For events at the same time, pick the larger unique event_id. Return user ID, event ID, and kind, sorted by user ID. The timestamps use one UTC format.
events
| user_id | event_id | recorded_at | kind |
|---|---|---|---|
| 1 | 10 | 2026-12-01T10:00:00Z | open |
| 1 | 12 | 2026-12-01T11:00:00Z | save |
| 1 | 13 | 2026-12-01T11:00:00Z | close |
| 1 | 20 | 2026-12-01T09:00:00Z | start |
| 2 | 22 | 2026-12-01T08:00:00Z | open |
Show hints (2)
- "RANK WITHIN USERS"
Give each user's events a separate order and choose one row from each group.
- "MAKE TIES DETERMINISTIC"
Start with time in descending order. Use the unique ID as the second sort key.
Show checked explanation
Use ROW_NUMBER() per user, ordered by timestamp descending and then event ID descending. Keep row number one in an outer query.
WITH ranked AS ( SELECT user_id, event_id, kind, ROW_NUMBER() OVER ( PARTITION BY user_id ORDER BY recorded_at DESC, event_id DESC ) AS row_num FROM events ) SELECT user_id, event_id, kind FROM ranked WHERE row_num = 1 ORDER BY user_id;
user_id | event_id | kind 1 | 13 | close 2 | 22 | open
Ran the query on SQLite 3.49 with the sample rows and edge cases.
Walkthrough
Events 12 and 13 are tied on time. Event 13 wins because it has the larger ID. Event 20 has an even larger ID but an earlier time. Numbering each user's events starts at one, so user 2 keeps event 22.
Common mistakes
- Using
MAX(event_id)as a proxy for the latest time. - Joining back to
MAX(recorded_at)and returning both tied events. - Ordering only by timestamp and leaving the tie unresolved.
Follow-up questions
- "What if you need all events tied at the latest timestamp?" Rank only by timestamp with
DENSE_RANK()and keep rank one. Sort the final result by event ID if you want stable display order. - "What if you need the latest successful event?" Filter to successful events inside the CTE before ranking. Filtering after ranking would drop users whose newest event failed.
What a strong answer covers
Explain the partition, the primary sort key, and the unique tiebreaker. Distinguish choosing one row from returning ties.
Open in interactive practice deck →