download

How do you get one latest event per user?

SQL~8 minReviewed 2 Dec 2026Free · No sign-in

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_idevent_idrecorded_atkind
1102026-12-01T10:00:00Zopen
1122026-12-01T11:00:00Zsave
1132026-12-01T11:00:00Zclose
1202026-12-01T09:00:00Zstart
2222026-12-01T08:00:00Zopen
Show hints (2)
  1. "RANK WITHIN USERS"

    Give each user's events a separate order and choose one row from each group.

  2. "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.

"SOLUTION · SQL"
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;
"OUTPUT"
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 →

Original OfferVibe question. SQLite window functions.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.