Per Event Durations With LEAD Window

Compute per-event durations by subtracting the current timestamp from LEAD of the next event, then aggregate total durations per endpoint outside.

SqlData Integrity

Code

snippet
-- Each event's duration = the next event's timestamp minus the current one: LEAD looks one row ahead
-- Window output cannot mix with same-level aggregation, so the outer query does the rollup
WITH api_events (endpoint, occurred_at) AS (
    VALUES
        ('GET /orders',  timestamptz '2026-06-01 09:00:00+00'),
        ('GET /orders',  timestamptz '2026-06-01 09:00:00.120+00'),
        ('GET /orders',  timestamptz '2026-06-01 09:00:00.450+00'),
        ('POST /orders', timestamptz '2026-06-01 09:00:01+00'),
        ('POST /orders', timestamptz '2026-06-01 09:00:01.300+00')
),
timed AS (
    SELECT
        endpoint,
        occurred_at,
        LEAD(occurred_at) OVER (PARTITION BY endpoint ORDER BY occurred_at)
            - occurred_at AS gap
    FROM api_events
)
SELECT
    endpoint,
    COUNT(*) AS events,
-- A session's last row has no next row, so its gap is NULL; SUM skips it and the report stays correct
    ROUND(SUM(EXTRACT(EPOCH FROM gap))::numeric, 3) AS total_seconds
FROM timed
GROUP BY endpoint
ORDER BY endpoint;

What the code does

At its core this is a single SELECT statement against api_events, gap and timed.

Breaking the statements into their working parts: a CTE (WITH … AS) that names an intermediate result before the main query; COUNT, SUM 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-level WHERE will not work — use an outer query or a CTE.

Using it

Run the statement against the api_events table.

Interactive Tools for This Topic

FAQ

Which objects does the SQL touch?
`api_events`, `gap`, `timed` — referenced directly, no join needed.