24. 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.
Essential
SQL 0/33
Git 0/15
Spark 0/20
Snowflake 0/22
Python 0/24
Need more practice in this area? Explore more questions →
DoorDash
TCS
X
Accenture
Adobe
Google
LinkedIn
Samsung
Datadog
Wix
Dropbox
Meta
OpenAI
Hulu
Uber
Anthropic
Amazon
ActivisionBlizzard
Vercel
Crypto.Com
Zscaler
DeutscheBank
Apple
GoDaddy
BMW
PayPal
Snowflake
AMD
Twilio
Atlassian
JPMorgan
NVIDIA
IBM
Databricks
Coinbase
Cisco
Robinhood
Twitter
Microsoft
Palantir
Netflix
VMware
Cloudflare
Stripe
Capital One
Splunk
Intel
SAP
Tesla
GitHub
JaneStreet
Bloomberg
Salesforce
Elastic
CGI
UBS
GitLab
Ubisoft
Slack
Nintendo
EY
Kayak
Lyft
Airbnb
Walmart
Revolut
Visa
Okta
HashiCorp
Instacart
Mastercard