Learn SQL/Advanced/Interview Patterns/SQL First Row per Group

SQL First Row per Group

SQL First Row per Group helps analysts rank rows earliest-first within each group and keep row one.

What & Why

The First Row per Group pattern is used to rank rows earliest-first within each group 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 each user's first recorded event.

iduser_idevent_namecreated_atproperties
1001101signup2024-01-15 09:12:00+00{"source":"organic"}
1002101activated2024-01-16 14:25:00+00{"step":"workspace"}
1003102signup2024-02-10 11:08:00+00{"source":"paid"}
1004103report_viewed2024-03-12 16:40:00+00{"report":"retention"}
EXAMPLE QUERY
WITH ranked_events AS (
  SELECT
    id AS event_id,
    user_id,
    event_name,
    created_at,
    ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at, id) AS event_rank
  FROM growth.events
)
SELECT user_id, event_id, event_name, created_at
FROM ranked_events
WHERE event_rank = 1
ORDER BY user_id;
RESULT — first event per user
user_idevent_idevent_namecreated_at
1011001signup2024-01-15 09:12:00+00
1021003signup2024-02-10 11:08:00+00
1031004report_viewed2024-03-12 16:40:00+00

The first row in user 101's partition is the signup event.

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario