The open-ended part tripped me up more than the SQL itself.
Start by clarifying the business definition of 'unhealthy' usage with the interviewer, then translate it into a precise SQL rule using session-level data. Write a query that aggregates daily usage per user, identifies users meeting the unhealthy criteria over the last 30 days, and computes the required metrics.
Pro tip: Always state your assumptions about the data schema (e.g., session start/end times, user_id, date) and edge cases (e.g., multiple sessions per day, timezone) before writing SQL—this shows you think like a data scientist, not just a coder.
Ask clarifying questions to define 'unhealthy' usage (e.g., continuous minutes, consecutive days) and confirm the table schema (columns like user_id, session_start, session_end). State any assumptions you make.
Write a subquery to calculate total continuous minutes per user per day, handling overlapping sessions if necessary. Use date functions to group by day.
Apply the rule (e.g., >120 minutes per day for at least 3 consecutive days) using window functions or self-joins to find users meeting the criteria within the last 30 days.
Calculate the count of unhealthy users, total active users (distinct users with any session in the last 30 days), and the percentage of unhealthy users.
Combine the subqueries into a single SQL statement that returns the three metrics. Use CTEs for readability and ensure date filters are applied correctly.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.