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.
Code
-- 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-levelWHEREwill not work — use an outer query or a CTE.
Using it
Run the statement against the api_events table.
Interactive Tools for This Topic
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.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.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.DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.
FAQ
- Which objects does the SQL touch?
- `api_events`, `gap`, `timed` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.