Explain how to carry a value forward to fill gaps (LOCF / last-observation-carried-forward) using window functions in a time series.

Last updated 13 July 2026

  • LOCF (last observation carried forward) fills NULL gaps with the most recent non-NULL value. LAG() alone can't do it because it only looks back one row.

  • Two-step trick: build a group id with COUNT(value) OVER (ORDER BY ts) (increments only on real values), then take MAX(value) OVER (PARTITION BY grp) to spread that value across the group.

  • Partition per series (e.g. per sensor) to avoid leakage. Some engines offer a shortcut: LAST_VALUE(... IGNORE NULLS).

  • https://medium.com/@rajeshkakiofc/deloitte-sql-interview-question-how-i-filled-missing-categories-with-window-functions-de84f0d0fb63
  • https://www.andrewvillazon.com/forward-fill-values-t-sql/
All Advanced SQL interview questions