Last event per user, with a tie-break
An SQL exercise from Querydrill. Solve it with a SQL editor in your browser, checked on the rows it returns and again on changed data, and it is checked the moment you submit.
Try it yourself
Return each user's last event: user_id, event and event_time. When two events of a user have the same time, the one with the higher id is the later one.
events (first 12 of 38 rows)
| id | user_id | event | event_time |
|---|---|---|---|
| 1 | 1 | visit | 2025-03-01 09:00:00 |
| 2 | 1 | signup | 2025-03-01 09:05:00 |
| 3 | 1 | purchase | 2025-03-01 09:20:00 |
| 4 | 2 | visit | 2025-03-01 10:00:00 |
| 5 | 1 | visit | 2025-03-01 15:00:00 |
| 6 | 1 | visit | 2025-03-02 10:00:00 |
| 7 | 3 | visit | 2025-03-02 12:00:00 |
| 8 | 3 | visit | 2025-03-02 12:40:00 |
| 9 | 1 | visit | 2025-03-03 08:00:00 |
| 10 | 1 | purchase | 2025-03-03 08:10:00 |
| 11 | 3 | signup | 2025-03-03 09:00:00 |
| 12 | 2 | visit | 2025-03-03 11:00:00 |
Free, no account needed. PostgreSQL runs in your browser and your answer is checked again on changed data.
What this exercise teaches
Two rows can share the same timestamp. Without a second sort key the database is free to return either one, and a join on MAX(event_time) returns both. Adding id as a tie-break makes the result exact and repeatable.
A hint if you get stuck
Sort by time and then by id, both descending, and keep the first row per user.
Background you need
Common mistakes on this exercise
- Returns two rows for a user whose last two events have the same time.
- Breaks the tie the wrong way: the lower id wins.
Each of these returns a result that looks plausible. The checker catches them because it runs your query on changed data as well.
Keep going on the practice page
Your first 8 exercises on Querydrill are free, with no account. The practice page has the full editor, timed mode and all the exercises in order. A free account shows 3 reference solutions a day; Pro unlocks every exercise, every solution, timed mode and the certificate.
Open this exerciseMore exercises in Advanced
- Above the average salary
- Rank within department
- Running revenue total
- Running total per customer
- Top earner per department
- Second highest salary
- Big spenders
- Levels in the reporting chain
- Dense rank
- Change from the previous order
- Days until the next order
- Moving average
- Share of revenue
- Share of the customer's total
- Each customer's first order
- Month over month
- Top two per category
- Orders above the customer's average
- Compared to the first order
- Salary quartiles
- Cumulative share of revenue
- Latest order per customer (DISTINCT ON)
- Two largest paid orders per customer (LATERAL)
- Most orders, ties included
- Year-over-year growth
- Price at the time of the order
- Read fields out of JSON
- One row per array element