# Top Users by Session Time

> They spent the most time here.

Canonical URL: <https://datadriven.io/problems/top_users_by_session_time>

Domain: SQL · Difficulty: medium · Seniority: L3

## Problem

Return the top 10 users by total session duration. Show each user's ID, username, and total duration, from highest to lowest.

## Worked solution and explanation

### Why this problem exists in real interviews

This tests a basic join with aggregation and ordering. Interviewers verify that you join before aggregating and select the correct columns from each table.

---

### Break down the requirements

#### Step 1: Join users to sessions

`JOIN user_sessions ON users.user_id = user_sessions.user_id` connects each user to their session records.

#### Step 2: Aggregate total duration per user

`GROUP BY users.user_id, username` with `SUM(session_duration_sec)` computes lifetime session time.

#### Step 3: Order and limit

`ORDER BY total_duration DESC LIMIT 10` returns the top 10 most engaged users.

---

### The solution

**Join, aggregate, and rank by total duration**

```sql
SELECT u.user_id, u.username, SUM(s.session_duration_sec) AS total_duration
FROM users u
JOIN user_sessions s ON u.user_id = s.user_id
GROUP BY u.user_id, u.username
ORDER BY total_duration DESC
LIMIT 10
```

> **Cost Analysis**
>
> The join produces up to 60M rows (every session matched to its user). The `GROUP BY` reduces this to 4M user-level rows. An index on `user_sessions(user_id)` is critical for join performance.

> **Interviewers Watch For**
>
> Candidates who use a LEFT JOIN when an INNER JOIN suffices. Since the prompt says "top 10 users by total session duration," users with zero sessions are irrelevant.

> **Common Pitfall**
>
> Forgetting to include `username` in the `GROUP BY` clause. While some engines allow it, standard SQL requires all non-aggregated SELECT columns in GROUP BY.

---

## Common follow-up questions

- What if you needed to convert seconds to hours in the output? _(Tests simple arithmetic: `SUM(session_duration_sec) / 3600.0`.)_
- What if users could have sessions with NULL duration? _(SUM ignores NULLs, but the business might want COALESCE to treat them as zero.)_
- How would you include users with zero sessions, showing 0 for duration? _(Switch to LEFT JOIN and use COALESCE(SUM(...), 0).)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/top_users_by_session_time)
- [SQL Interview Questions](https://datadriven.io/sql-interview-questions)
- [Data Engineering Interview Prep Guide](https://datadriven.io/data-engineer-interview-prep)
- [Daily Challenge](https://datadriven.io/daily)

---

Source: DataDriven (https://datadriven.io). 100% free data engineering interview prep. Live code execution against Postgres 16, Python 3.11, and Spark sandboxes. No paywall, no premium tier, no signup gate.