Last Seen

An easy SQL interview practice problem on DataDriven. Write the query and run it against a real database, with instant feedback.

Domain
SQL
Difficulty
easy
Seniority
L3
Asked in
Moore Capital Management

Problem

The retention team is building a recency model and needs each user's most recent session start alongside their user ID, with the roster running from the lowest user ID up to the highest.

Everyone has a most recent session.

Tables

user_sessions

Columns: session_id INTEGER, user_id INTEGER, device_id INTEGER, session_start TEXT, session_duration_sec INTEGER, pages_viewed INTEGER

user_sessions: 10 of 200 rows
session_iduser_iddevice_idsession_startsession_duration_secpages_viewed
70611972302026-02-02 01:00:00533
71222942592026-03-03 02:00:00766
71833912882026-04-04 03:00:00999
72444883172026-05-05 04:00:0012212
73055853462026-06-06 05:00:0014515
73666823752026-07-07 06:00:0016818
74277794042026-08-08 07:00:0019121
7488876NULL2026-09-09 08:00:0021424
75499734622026-01-10 09:00:0023727
761010704912026-02-11 10:00:0026030

Expected output

First 5 of 59 rows
user_idlatest_session_start
1002026-09-01 08:00:00
1972026-08-06 13:00:00
2942026-09-07 14:00:00
3912026-08-16 19:00:00
4882026-09-05 20:00:00

Worked solution and explanation

What this really is

Under the retention costume this is a grain-collapse: one user owns many sessions, and you have to return exactly one row per user carrying the freshest timestamp. Everyone reaches for something. The tell is whether you reach for the cheap thing. Candidates who self-join the table back to itself on the latest date, or lean on DISTINCT, are solving a problem that was never here. The trap is subtler than it looks: forget to collapse per user and MAX quietly hands you a single global date for the whole table, which looks like a valid answer until someone checks the row count.


Walking through it

Step 1: Collapse to one row per user

GROUP BY user_id folds every one of a user's sessions into a single group. This is the step that guarantees one output row per user; skip it and the aggregate spans the entire table.

Step 2: Take the latest start per group

MAX(session_start) inside each group returns that user's latest start. Because session_start sorts lexically as an ISO timestamp string, MAX picks the most recent moment without any date parsing.

Step 3: Order for stable output

ORDER BY user_id makes the output deterministic so it lines up with the expected preview. The sort is presentation only; it does not change which rows come back.


The solution

MAX aggregation per user
SELECT user_id, MAX(session_start) AS latest_session_start
FROM user_sessions
GROUP BY user_id
ORDER BY user_id

Common follow-up questions