Skip to content
DocumentationLakehouse

SESSIONIZE

SESSIONIZE assigns ordered rows to sessions separated by a period of inactivity. Use it to label events with a session ID or to calculate one result row per session without building the usual lag, cumulative-sum, and grouping pipeline.

Run these statements through Altertable's SQL engine.

First example

Suppose an event table contains one row for each user action:

SQL
WITH events(user_id, ts, event) AS (
VALUES
(1, TIMESTAMP '2024-01-01 10:00:00', 'view'),
(1, TIMESTAMP '2024-01-01 10:10:00', 'click'),
(1, TIMESTAMP '2024-01-01 10:50:00', 'purchase'),
(2, TIMESTAMP '2024-01-01 10:00:00', 'view')
)
SELECT
user_id,
ts,
event,
session_start,
session_end,
session_id
FROM events
SESSIONIZE (
PARTITION BY user_id
ORDER BY ts
GAP INTERVAL 30 MINUTE
)
ORDER BY user_id, ts;

The first two events for user 1 belong to session 1 because they are 10 minutes apart. The 40-minute gap before purchase starts session 2. Session IDs restart at 1 for each user.

  • PARTITION BY user_id creates an independent event stream for each user.
  • ORDER BY ts defines event order.
  • GAP INTERVAL 30 MINUTE starts a new session after more than 30 minutes of inactivity.
  • session_start and session_end contain the first and last time-key values in the session.
  • session_id is a 1-based number within each partition.

Operator syntax

The supported FROM-clause shape is:

SQL
FROM input_relation [input_alias]
SESSIONIZE (
[PARTITION BY partition_column [, ...]]
ORDER BY time_column [, tie_breaker_column ...]
GAP interval_expression [GRANULARITY unit]
[DEDUPLICATE BY column [, ...]
KEEP { FIRST BY (column [ASC | DESC] [NULLS FIRST | LAST] [, ...])
| LAST BY (column [, ...]) }]
[SESSION_ID AS alias]
[SESSION_START AS alias]
[SESSION_END AS alias]
[ROW_NUMBER [AS alias]]
[MEASURES measure_expression AS output_name [, ...]]
[ONE ROW PER SESSION]
)
[session_alias]

ORDER BY and GAP are required. PARTITION BY is optional. MEASURES can only be used with ONE ROW PER SESSION. The metadata options (SESSION_ID, SESSION_START, SESSION_END, and ROW_NUMBER) can appear in any order after deduplication options and before MEASURES or ONE ROW PER SESSION.

The source relation must appear immediately before SESSIONIZE. The result can be aliased after the clause:

SQL
SELECT s.user_id, s.session_id
FROM events AS e
SESSIONIZE (
PARTITION BY user_id
ORDER BY ts
GAP INTERVAL 30 MINUTE
) AS s;

Common SQL constructs such as CTEs, subqueries, joins, outer filters, grouping, and aliases can surround the operator.

How sessions are formed

Within each partition, SESSIONIZE sorts rows by the ORDER BY columns and compares each time-key value with the preceding value. By default, a new session starts when:

Plain text
current_time > previous_time + GAP

Equality stays in the current session. With a 30-minute gap, events exactly 30 minutes apart belong to the same session; an event 30 minutes and one second later starts a new one.

The comparison uses consecutive events, not the session start. A session can therefore last longer than the gap as long as each event arrives within the gap after the previous event.

With GRANULARITY, the comparison counts unit boundaries instead of exact elapsed time. If DEDUPLICATE BY is present, only surviving rows participate in gap comparisons and determine session boundaries.

Remove duplicate events

Use DEDUPLICATE BY with KEEP to choose one row for each duplicate key before assigning sessions. For example, keep the earliest received copy of each event:

SQL
SELECT *
FROM events
SESSIONIZE (
PARTITION BY user_id
ORDER BY ts, event_id
GAP INTERVAL 30 MINUTE
DEDUPLICATE BY event_id KEEP FIRST BY (received_at ASC NULLS LAST)
)
ORDER BY user_id, ts, event_id;

Deduplication happens within each PARTITION BY partition. If the same event_id occurs for two users, each user keeps a copy. It is equivalent to global deduplication by event ID only when every copy has the same partition values.

  • KEEP FIRST BY (columns) keeps the first row under the specified sort order. It accepts ASC, DESC, NULLS FIRST, and NULLS LAST, using DuckDB's defaults when omitted.
  • KEEP LAST BY (columns) keeps the greatest tuple, with NULL ranked lowest. It does not accept sort direction or null-order modifiers.
  • Ties on all KEEP columns are resolved by the operator's ORDER BY. If those columns also tie, the surviving row is unspecified.
  • Null deduplication keys compare equal, as in GROUP BY.
  • Deduplication and KEEP keys must be input columns. KEEP is required; parentheses are optional for a single KEEP key.

Dropped rows are absent from both output modes. They do not bridge or split sessions and do not contribute to row numbers, session boundaries, or measures.

Choose the output mode

Preserve every input row

Row-preserving mode is the default. It returns every surviving input row, with the input columns in their original order, followed by session_start, session_end, and session_id (or their aliases):

SQL
SELECT *
FROM events
SESSIONIZE (
PARTITION BY user_id
ORDER BY ts
GAP INTERVAL 30 MINUTE
);

Every row in the same session receives the same metadata. session_start and session_end are the first and last time-key values, not calculated window boundaries such as session_end + GAP.

Use this mode when downstream logic still needs individual events:

SQL
WITH labeled_events AS (
SELECT *
FROM events
SESSIONIZE (
PARTITION BY user_id
ORDER BY ts, event_id
GAP INTERVAL 30 MINUTE
)
)
SELECT *
FROM labeled_events
WHERE session_id = 1
ORDER BY user_id, ts, event_id;

Number rows within each partition

Add ROW_NUMBER to append a BIGINT column named row_number after the session ID, or use ROW_NUMBER AS alias to name it:

SQL
SELECT *
FROM events
SESSIONIZE (
PARTITION BY user_id
ORDER BY ts, event_id
GAP INTERVAL 30 MINUTE
DEDUPLICATE BY event_id KEEP FIRST BY (received_at ASC NULLS LAST)
ROW_NUMBER AS event_number
)
ORDER BY user_id, event_number;

Numbering starts at 1 in each partition and counts only rows that survive deduplication. It continues across session boundaries. Add stable tie-breakers to ORDER BY when row numbering must be deterministic.

ROW_NUMBER is optional and cannot be used with ONE ROW PER SESSION.

Return one row per session

Add ONE ROW PER SESSION to emit session metadata without preserving the input rows:

SQL
SELECT *
FROM events
SESSIONIZE (
PARTITION BY user_id
ORDER BY ts
GAP INTERVAL 30 MINUTE
ONE ROW PER SESSION
)
ORDER BY user_id, session_id;

The output contains, in order:

  1. The PARTITION BY columns, when present.
  2. session_start, session_end, and session_id, or their aliases.
  3. The explicitly declared MEASURES, when present.

No event count is added automatically. Add count(*) as a measure when you need one.

Calculate session measures

MEASURES calculates values across all surviving rows in a session. Every measure needs an AS alias, and the clause requires ONE ROW PER SESSION:

SQL
WITH events(user_id, ts, event, amount) AS (
VALUES
(1, TIMESTAMP '2024-01-01 10:00:00', 'view', 0),
(1, TIMESTAMP '2024-01-01 10:10:00', 'purchase', 49),
(1, TIMESTAMP '2024-01-01 10:50:00', 'view', 0)
)
SELECT *
FROM events
SESSIONIZE (
PARTITION BY user_id
ORDER BY ts
GAP INTERVAL 30 MINUTE
MEASURES
count(*) AS event_count,
sum(amount) AS revenue,
FIRST(event) AS first_event,
event AS last_event,
list(event) AS events
ONE ROW PER SESSION
)
ORDER BY user_id, session_id;

Measure expressions support:

  • Aggregates such as count, sum, avg, min, max, list, and count(DISTINCT ...).
  • FIRST(expression) and LAST(expression) for values from the first and last rows.
  • A bare input column, which returns its value from the last row of the session.
  • PARTITION BY columns, which are constant throughout a session.
  • Constants, scalar functions, and arithmetic composed from these values.

Measures use whole-session semantics. Pattern-only expressions from MATCH_RECOGNIZE, including pattern variables, CLASSIFIER(), MATCH_NUMBER(), PREV, NEXT, RUNNING, and FINAL, are not supported.

Aggregate FILTER clauses and aggregate-local ORDER BY clauses are not supported in SESSIONIZE measures. When you need them, preserve the sessionized rows and aggregate by the partition columns and session_id in an outer query.

Define the event streams

PARTITION BY

PARTITION BY splits the input into independent event streams:

SQL
PARTITION BY user_id, device_id

Sessions never cross a partition boundary. Without PARTITION BY, the entire input is treated as one stream.

Partition expressions must be input columns. In summary mode, partition columns appear first in the result and can be referenced directly in measures.

ORDER BY

The first ORDER BY column is the time key:

SQL
ORDER BY ts, event_id

It must be an ascending input column with a DATE, TIMESTAMP, or TIMESTAMPTZ type. Supported timestamp precisions include seconds, milliseconds, microseconds, and nanoseconds.

A null time key on a surviving row or temporal overflow causes a runtime error. Null time keys on rows removed by deduplication do not cause an error.

Additional columns are tie-breakers. Add a stable tie-breaker when multiple events can have the same timestamp and their relative order matters.

GAP

GAP sets the maximum inactivity period within a session:

SQL
GAP INTERVAL 30 MINUTE

The expression must be a non-null, strictly positive, foldable DuckDB INTERVAL. Dynamic per-row gaps are not supported.

Count gap boundaries with GRANULARITY

Add GRANULARITY unit to compare date_diff(unit, previous_time, current_time) with the gap expressed in that unit:

SQL
GAP INTERVAL 30 MINUTE GRANULARITY SECOND

For example, events at 00:00:00.1 and 00:30:00.9 are 1,800.8 seconds apart but cross 1,800 second boundaries. They stay in the same session with GRANULARITY SECOND; the default exact-time comparison would split them.

  • Supported units are MICROSECOND, MILLISECOND, SECOND, MINUTE, HOUR, and DAY, including DuckDB's date_diff spellings such as seconds and ms. Units are case-insensitive; calendar units such as WEEK, MONTH, and YEAR are not supported.
  • The gap must be a fixed-length interval and a whole number of the chosen units. Days count as 24 hours; months and years are not allowed. For example, GAP INTERVAL 90 SECOND GRANULARITY MINUTE is rejected.
  • TIMESTAMPTZ keys support only MICROSECOND, MILLISECOND, and SECOND, because coarser date_diff boundaries depend on the time zone.
  • Boundaries are counted by flooring epoch values to the unit, including before 1970. DATE and second-, millisecond-, or nanosecond-precision timestamp keys are compared as TIMESTAMP.
  • With granularity, an infinite timestamp never continues a session.

Output names and ordering

Rename metadata with SESSION_ID AS, SESSION_START AS, or SESSION_END AS. For example, an input column named session_id can remain in the output if the generated session ID has a different name:

SQL
SELECT *
FROM events
SESSIONIZE (
PARTITION BY session_id
ORDER BY ts
GAP INTERVAL 30 MINUTE
SESSION_ID AS gap_session_id
SESSION_START AS gap_start
SESSION_END AS gap_end
);

Aliases change only the emitted metadata names. They work in both output modes and do not change column order.

Final metadata names, including an optional row-number column, must not collide with each other or with input columns in row-preserving mode. In summary mode, they must not collide with partition columns or measure aliases. Measure aliases must also be distinct from partition columns and each other. Rename the metadata or the conflicting input columns to resolve a collision.

Result order is not guaranteed. Add an outer ORDER BY whenever downstream behavior depends on row order:

SQL
SELECT *
FROM events
SESSIONIZE (
PARTITION BY user_id
ORDER BY ts, event_id
GAP INTERVAL 30 MINUTE
)
ORDER BY user_id, session_id, ts, event_id;

Persist session results

CREATE VIEW and CREATE MACRO cannot store a SESSIONIZE clause. To persist results, use CREATE TABLE AS SELECT ... SESSIONIZE (...), or run the clause inline when querying.

Learn more

  • JOURNEYS: discover observed paths through event sequences.
  • MATCH_RECOGNIZE: find more complex ordered event patterns.
  • SQL Explorer: run and refine session queries interactively.
  • SQL engine: learn about Altertable's DuckDB SQL dialect.