Learn SQL/Advanced/Interview Patterns/SQL Latest Row per Customer

SQL Latest Row per Customer

SQL Latest Row per Customer helps analysts rank rows newest-first within each entity and keep row one.

What & Why

The Latest Row per Customer pattern is used to rank rows newest-first within each entity and keep row one. This keeps the SQL aligned with one concrete business question and makes the result grain explicit before the query is reused.

See How It Works

BUSINESS QUESTION

Growth wants the latest session recorded for every user.

iduser_idstarted_atended_atpage_viewsdevice
50011012024-01-16 14:20:00+002024-01-16 14:52:00+008desktop
50021022024-02-10 11:10:00+002024-02-10 11:18:00+003mobile
50031032024-03-13 08:10:00+002024-03-13 09:04:00+0012desktop
50041042024-04-03 12:00:00+00NULL1tablet
50051052024-04-04 09:00:00+002024-04-04 09:21:00+007mobile
50061062024-04-05 10:15:00+002024-04-05 10:42:00+005tablet
50071072024-04-06 13:05:00+002024-04-06 13:38:00+0010desktop
EXAMPLE QUERY
WITH ranked_sessions AS (
  SELECT
    id AS session_id,
    user_id,
    started_at,
    device,
    ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY started_at DESC, id DESC) AS session_rank
  FROM growth.sessions
)
SELECT user_id, session_id, started_at, device
FROM ranked_sessions
WHERE session_rank = 1
ORDER BY user_id;
RESULT — latest session per user
user_idsession_idstarted_atdevice
10150012024-01-16 14:20:00+00desktop
10250022024-02-10 11:10:00+00mobile
10350032024-03-13 08:10:00+00desktop
10450042024-04-03 12:00:00+00tablet
10550052024-04-04 09:00:00+00mobile
10650062024-04-05 10:15:00+00tablet
10750072024-04-06 13:05:00+00desktop

Each representative user has one session, so all session rows survive.

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario