Nested Subquery for Latest Record
Beginner Mode
Objective
Given a table named events with the following columns:
| Column | Type | Description |
|---|---|---|
| id | INTEGER | The unique identifier for each event |
| event_name | VARCHAR | The name of the event |
| user_id | INTEGER | The identifier of the user associated with the event |
| event_date | DATE | The date when the event occurred |
| status | VARCHAR | The status of the event |
Write an SQL query to fetch the most recent event for each user. The result should include the event_name, user_id, event_date, and status of these latest events, sorted in ascending order by user_id.
Additional information
- Each user may have multiple events recorded in the
eventstable. - The
event_datefor each event is unique per user. - If a user has multiple events on the same latest date, you can return any one of them.
- Ensure that your query is optimized for performance, especially with large datasets.
Examples
Example 1:
Output:
Input:
| events | ||||
|---|---|---|---|---|
| event_date | event_name | id | status | user_id |
| 2023-01-01 | login | 1 | success | 101 |
| 2023-01-02 | purchase | 2 | completed | 101 |
| 2023-01-01 | login | 3 | success | 102 |
| 2023-01-03 | logout | 4 | success | 101 |
| 2023-01-02 | purchase | 5 | failed | 102 |
| event_date | event_name | status | user_id |
|---|---|---|---|
| 2023-01-03 | logout | success | 101 |
| 2023-01-02 | purchase | failed | 102 |
Code Environment
Sign in or try as guest to run your code.
Track
| Question | Difficulty | Company | Access |
|---|
Need more practice in this area? Explore more questions →
DoorDash