Gap And Islands Consecutive Sessions
Identify consecutive session groups using the gap and islands technique with row number difference for grouping.
Code
WITH numbered AS (
SELECT
user_id,
session_date,
ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY session_date) AS rn
FROM user_sessions
),
grouped AS (
SELECT
user_id,
session_date,
session_date - rn AS grp
FROM numbered
)
SELECT
user_id,
MIN(session_date) AS start_date,
MAX(session_date) AS end_date,
COUNT(*) AS consecutive_days
FROM grouped
GROUP BY user_id, grp
ORDER BY user_id, start_date;How it works
What runs is SELECT, with user_sessions, numbered and grouped as the object involved.
Mechanically, the statements are built from: a CTE (WITH … AS) that names an intermediate result before the main query; COUNT, MIN, MAX aggregation; a GROUP BY that collapses matching rows into one output row per group; a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order.
What to watch for
- Window functions evaluate after
WHERE/GROUP BY, so filtering on their output in the same-levelWHEREwill not work — use an outer query or a CTE.
Using it
The user_sessions table is the working surface here.
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which tables appear in this script?
- `user_sessions`, `numbered`, `grouped`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.