How to Implement Gap Filling and Forward Fill in SQL
Generate missing time buckets and carry the last known value forward in SQL, so charts and reports have a continuous series without holes.
On this page
Introduction
A time series with no events in a bucket has no row, so a chart drawn from it has an invisible gap and an average computed over it is wrong, because the missing buckets are silently excluded. Gap filling generates the missing buckets with zero, null or a carried-forward value, so the series is continuous and the aggregation is correct. PostgreSQL makes this straightforward with generate_series for the buckets and a window function to carry the last known value forward when zero is not the right fill.
Why Gaps Appear and Why They Matter
Aggregating events by time bucket returns only buckets that had events. A quiet hour produces no row, which a chart skips and a per-bucket average that divides by the row count silently ignores. The result understates the period and misleads anyone reading a trend.
The fix has two parts: generate every bucket in the range, so the series is continuous, and decide what value each empty bucket takes. For counts, zero is usually right. For a gauge such as a balance or a temperature, the last known value carried forward is usually right. The choice is semantic, not technical.
# the gap problem
SELECT date_trunc('hour', created_at) AS h, count(*) FROM events
GROUP BY 1 ORDER BY 1;
# only hours WITH events appear -> a chart has gaps, an average is wrong
# fix: generate all buckets, then fill:
# counts -> 0 (no events happened)
# gauges -> last value carried forward (state persisted)
Generating the Buckets
generate_series produces every timestamp in a range at a given step, which is the bucket set. Left-join it to the aggregated data so every bucket appears, with the aggregate present where it exists and null where it does not. This is the outer side of the join; the generated series is the driver.
Choose the step to match the reporting granularity, and bound both ends explicitly so the series does not run to now unintentionally. A series from a fixed start to a fixed end is reproducible; a series to now() changes every time it runs and makes the result non-deterministic.
-- Every hour in a fixed range, left-joined to the real counts.
WITH buckets AS (
SELECT generate_series(
$1::timestamptz, -- start
$2::timestamptz, -- end (explicit, not now())
interval '1 hour'
) AS bucket
),
counts AS (
SELECT date_trunc('hour', created_at) AS bucket, count(*) AS n
FROM events
WHERE created_at >= $1 AND created_at < $2
GROUP BY 1
)
SELECT b.bucket, COALESCE(c.n, 0) AS events
FROM buckets b
LEFT JOIN counts c USING (bucket)
ORDER BY b.bucket;
Forward Fill with LAST_VALUE
For a gauge, an empty bucket should carry the last known value forward. The window function for this is a running “last non-null value”: order by the bucket and take the most recent non-null value at or before each row. In PostgreSQL, the IGNORE NULLS option on window functions does this directly.
Build the series with the left join as before, leave the empty buckets null, then apply the forward fill. The order matters: you cannot fill forward until you have the whole series ordered, so the fill is a second pass over the joined result, usually in a subquery or CTE.
-- Forward fill: carry the last known balance to empty hours.
WITH buckets AS (
SELECT generate_series($1::timestamptz, $2::timestamptz, interval '1 hour') AS bucket
),
joined AS (
SELECT b.bucket, s.balance
FROM buckets b
LEFT JOIN account_snapshots s ON s.bucket = b.bucket -- null when no snapshot
)
SELECT bucket,
LAST_VALUE(balance) IGNORE NULLS
OVER (ORDER BY bucket ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS filled
FROM joined
ORDER BY bucket;
Forward Fill Without IGNORE NULLS
Older engines, or dialects without IGNORE NULLS, use the “grouping trick”: create a group id that changes whenever a non-null value appears, then take the first value in the group. The running max of a non-null marker gives the group id, and a window max or first_value over the group gives the carried value.
The trick is more verbose but portable and worth knowing because it works on engines that lack the direct option. It also makes the mechanism explicit, which is useful when the fill has a subtle requirement such as filling only within a bounded gap.
-- Portable forward fill: group id increments at each known value.
WITH joined AS ( /* bucket + nullable value, as above */ ),
marked AS (
SELECT bucket, value,
COUNT(value) OVER (ORDER BY bucket) AS grp -- increments on non-null
FROM joined
)
SELECT bucket,
MAX(value) OVER (PARTITION BY grp) AS filled -- carry within group
FROM marked
ORDER BY bucket;
Filling Only Within a Bounded Gap
Carrying a value forward indefinitely can be wrong: after a sensor goes offline for a week, forward-filling its last reading for the whole week fabricates data. Bound the fill: carry forward only for gaps up to a maximum length, and leave longer gaps as null or as an explicit “no data” marker.
Implement the bound by tracking the gap length from the last known value and filling only when it is within the limit. This keeps the chart continuous for brief holes without inventing values across a real outage, which is a semantic decision the report should make explicitly.
-- Fill gaps up to 3 buckets; leave longer gaps null.
WITH joined AS ( /* bucket + nullable value */ ),
marked AS (
SELECT bucket, value,
COUNT(value) OVER (ORDER BY bucket) AS grp,
ROW_NUMBER() OVER (ORDER BY bucket) AS rn
FROM joined
),
grouped AS (
SELECT bucket, value, grp,
MIN(rn) FILTER (WHERE value IS NOT NULL) OVER (PARTITION BY grp) AS anchor_rn
FROM marked
)
SELECT bucket,
CASE WHEN grp = 0 OR rn - anchor_rn > 2 THEN NULL ELSE MAX(value) OVER (PARTITION BY grp) END AS filled
FROM grouped
ORDER BY bucket;
Performance and Materialisation
generate_series is cheap, but the join and the window fill over a long range still cost work proportional to the number of buckets. For a dashboard queried often, materialise the filled series into a table refreshed on a schedule, so the read is a simple scan of pre-filled rows rather than the generation and fill each time.
Size the bucket count to the range: a year at hourly buckets is nearly nine thousand rows, fine, but a year at per-second buckets is thirty million, which you should not generate per request. Match the granularity to the question, and pre-aggregate coarser series for longer ranges.
# bucket count sanity
hourly, 1 year ~ 8,760 rows -> fine to generate per query
minute, 1 year ~ 525,600 rows -> pre-aggregate to hourly for long views
second, 1 year ~ 31.5M rows -> never per request; pre-aggregate
# for a hot dashboard: materialise the filled series, refresh on a schedule
Common Pitfalls and Conclusion
Do not fill a gauge with zero; that fabricates a drop to zero. Do not forward-fill across an unbounded gap; bound it. Do not generate a series to now(), which makes the result non-deterministic. Do not generate per-second buckets for a year on every request. And do not forget that the fill is semantic: decide per metric whether an empty bucket is zero, carried forward, or genuinely unknown.
Gap filling makes a time series continuous so charts have no invisible holes and averages are correct. Generate the buckets with generate_series, left-join the data, fill counts with zero and gauges with a bounded forward fill using LAST_VALUE IGNORE NULLS or the grouping trick, and materialise the series when it is queried often. Then a report shows the quiet periods instead of hiding them.
Check a known empty bucket to confirm the fill behaves as intended.
Sources: PostgreSQL: generate_series, PostgreSQL: Window functions, PostgreSQL: Date/time functions.
FAQ
- When should I forward fill instead of fill with zero?
- For gauges that represent a persistent state, such as a balance or a temperature, where an empty bucket means the value did not change. Fill counts with zero, because no events genuinely means zero events, and reserve forward fill for state-like measures.
- Why bound the forward fill?
- Because filling forward across a long outage fabricates data. Carry the last value only for gaps within a maximum length, and leave longer gaps null or marked as no-data, so the chart shows the real outage instead of inventing a steady value.
Report a problem with this articleOpens a pre-filled issue on GitHub.