Lesson 10 of 13 · 15m
Time-Series and Gap Analysis
generate_series scaffolds the missing buckets, LAG plus a running SUM sessionizes gaps-and-islands, and timestamptz plus explicit zones keep reports honest.
SELECT date_trunc('hour', ts) AS hr, count(*) FROM events GROUP BY 1 produces exactly the rows that exist. Hours with zero events don't appear — the group doesn't exist because no row fed it. Ship that to a chart and the chart draws a line that jumps across the dead zone as if nothing ever stopped. The fix isn't application-side zero-filling. It's generate_series: build the complete scaffold of hours first, then LEFT JOIN the facts onto it.
SELECT hr, count(e.*) AS events
FROM generate_series('2026-11-01'::timestamptz, '2026-11-02'::timestamptz, interval '1 hour') hr
LEFT JOIN events e ON date_trunc('hour', e.ts) = hr
GROUP BY hr ORDER BY hr;The series is authoritative; the data decorates it. Every chart-query you write for sparse data should start from the series, not the table. The scaffold also makes the bucket width a parameter rather than a table property — the same query serves a five-minute dashboard and a daily export by changing interval '1 hour', and empty buckets carry real zeros instead of missing rows, so downstream count/sum/avg behave uniformly. Note the GROUP BY hr is over the series: grouping date_trunc('hour', e.ts) directly rebuilds the gap you just removed.
The wrong model: bucket what's there
"GROUP BY the hour and let missing hours stay missing" is how dashboards end up showing a steady line during a three-hour outage — the zeros are the most important datapoint and they're the ones you skipped. The same model produces its mirror-image bug in the other direction: averaging sampled rows as if samples were uniform. avg(cpu_pct) over irregular samples is not the average CPU over time — a burst sampled densely outweighs hours of sparse quiet. Time-weighted averaging requires weighting by the interval each sample covers (LAG to get each sample's duration, sum(x * dt) / sum(dt)), not a bare avg().
Sessionization: the gaps-and-islands pattern
"Group events into sessions where a gap over 30 minutes starts a new session" is the canonical analytics problem, and the pure-SQL answer is a two-window composition:
WITH flagged AS (
SELECT user_id, ts,
CASE WHEN ts - LAG(ts) OVER (PARTITION BY user_id ORDER BY ts)
> interval '30 minutes' THEN 1 ELSE 0 END AS new_session
FROM events
)
SELECT user_id, ts,
sum(new_session) OVER (PARTITION BY user_id ORDER BY ts) AS session_id
FROM flagged;LAG computes each event's gap from the previous; sum() over the flag as a running total assigns each event a session number that increments at every gap. Two window functions, one pass — the join-based versions of this pattern are the reason sessionization has a reputation as expensive.
The same gaps-and-islands machinery answers "streaks of consecutive login days," "contiguous uptime intervals," and "subscription periods with no lapses" — flag the boundary, running-sum the flag.
When you outgrow plain SQL
date_trunc is fine until 'last 30 days, one bucket per 15 minutes' means 2,880 buckets over hundreds of millions of rows. That's the workload TimescaleDB was built for: create_hypertable partitions by time behind the scenes, time_bucket('15 minutes', ts) replaces date_trunc, and continuous aggregates materialize the rolled-up result incrementally as raw data lands — the dashboard reads pre-computed buckets instead of rescanning raw events. The honest tradeoff: another extension, its own refresh semantics, its own failure modes. Reach for it when the raw-scan query is the bottleneck you can measure, not before.
Time zones are not a footnote
date_trunc('day', ts) buckets in the session TimeZone. A 'daily revenue' report run by an ETL job in UTC and a dashboard in America/New_York disagree by design — same rows, different days. Store timestamptz (absolute instant), and make every bucketing query state its zone: date_trunc('day', ts AT TIME ZONE 'America/New_York') buckets by New York wall-clock. The class of bug here — reports that drift an hour every DST transition — is entirely avoidable and entirely common.
What to actually do
- Sparse-bucket reports:
generate_seriesscaffold +LEFT JOIN— never group the raw table alone. - Streaks, sessions, contiguous intervals:
LAGflag + runningsum()— the gaps-and-islands pattern. - Rate/level averages over irregular samples: time-weighted
sum(x*dt)/sum(dt), notavg(). - Bucketing always carries an explicit zone; store
timestamptz, nevertimestamp. - When raw scans are the measured bottleneck, evaluate TimescaleDB hypertables + continuous aggregates — before that,
date_truncand good indexes carry further than expected.
Was this lesson helpful?
Keep reading
Related articles from the SudoSecurity blog.
PostgreSQL 19 Is Out. REPACK Kept My Writes Running. The Docker Upgrade Will Stop Your App.
PostgreSQL 19 shipped on November 19 with REPACK (CONCURRENTLY), which removes table bloat without blocking writes. I measured it against VACUUM FULL, ran the upgrade from 18, and checked what breaks for self-hosters: Docker tags that refuse to start, a config setting that stops the server, and...
PostgreSQL Fixed 52 CVEs in One Release. The Upgrade Is the Easy Part.
PostgreSQL 18.7, 17.12, 16.16, 15.20 and 14.25 fix 52 security vulnerabilities, almost twice August's record of 28. The binary swap took under a second in my test. The post-update steps are where the work is, and one of them makes some indexes several times bigger.
What PostgreSQL 15 Changed
A new version of the popular open-source database PostgreSQL is now available, offering performance improvements over PostgreSQL 14 and new functions and capabilities for managing workloads in local and distributed deployments. Released on October 13 by the PostgreSQL Global Development Group,…
PHP API Performance: N+1 Queries, cURL, and Connection Pools
A PHP API case study: fixing an N+1 query, twenty serial cURL calls, missing connection pooling, and stats recalculated on every request with Redis caching.