Skip to content

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_series scaffold + LEFT JOIN — never group the raw table alone.
  • Streaks, sessions, contiguous intervals: LAG flag + running sum() — the gaps-and-islands pattern.
  • Rate/level averages over irregular samples: time-weighted sum(x*dt)/sum(dt), not avg().
  • Bucketing always carries an explicit zone; store timestamptz, never timestamp.
  • When raw scans are the measured bottleneck, evaluate TimescaleDB hypertables + continuous aggregates — before that, date_trunc and good indexes carry further than expected.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.