Skip to main content
SQL-ADVANCED5 MIN READ

Build Session Boundaries With LAG and a Running Sum

Use LAG plus a running SUM to assign session IDs from event gaps.

You have one row per product event and need to assign session IDs whenever the gap between consecutive events for the same user exceeds 30 minutes. Partition by user, compare each row to its predecessor with lag(), then convert session starts into a cumulative identifier with a running sum. The common trap is to self-join events to previous events, which quickly becomes hard to reason about and makes later filtering fragile when timestamps tie or event volume spikes. Step 1 Use lag(event_at) over (partition by user_id order by event_at, event_id) to expose the previous event timestamp for the same user.…

Read the full lesson

Sign up free — one personalized lesson every day, matched to your role and goals.

Already have an account? Sign in

← Back to library
Contact us