Write SQL for session analytics
ShopifyData Engineer · Technical ScreenLast updated
This problem tests your ability to clean event-based log data, perform time-series aggregation, and calculate session-level metrics using SQL window functions.
Problem Statement
You are working with a table named page_views that tracks user activity on an e-commerce platform. Because of network retries, the table contains duplicate entries for the same event. A session is defined as a sequence of activity where no two consecutive page views are more than 30 minutes apart.
Schema
Table: page_views
event_id: VARCHAR (Primary Key)user_id: VARCHARpage_url: VARCHARtimestamp: TIMESTAMP
Task
- Deduplicate the data based on
event_id. - Assign a
session_idto each activity. A new session starts if the time elapsed since the user's previous page view is greater than 30 minutes. - Output a summary table containing
user_id,session_id,session_start_time,session_end_time, andpage_count(number of unique pages visited).
Example
Input:
| event_id | user_id | timestamp |
|---|---|---|
| 1 | A | 2023-10-01 10:00:00 |
| 2 | A | 2023-10-01 10:15:00 |
| 3 | A | 2023-10-01 10:50:00 |
Output:
| user_id | session_id | session_start | session_end | page_count |
|---|---|---|---|---|
| A | 1 | 10:00:00 | 10:15:00 | 2 |
| A | 2 | 10:50:00 | 10:50:00 | 1 |
Constraints
- Assume
timestampis in UTC. - Your solution should handle high volumes of data efficiently using standard window functions.
- Consider cases where a user has multiple sessions in a single day.
Hints
Hint 1
Use a Common Table Expression (CTE) to perform a `DISTINCT` operation or use `ROW_NUMBER()` to filter out duplicate `event_id`s.
Hint 2
Use the `LAG()` window function to calculate the time difference between the current row's timestamp and the previous row's timestamp for each user.
Hint 3
Use a cumulative sum over a boolean flag (where the gap > 30 minutes) to generate a unique session identifier for each user.
Follow-up questions
- How would you modify your query to extract the 'product_id' parameter from the `page_url` string?
- If the dataset grows to billions of rows, how would you partition the `page_views` table to optimize the performance of this sessionization query?
- How would you account for sessions that span across midnight?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.