How do LAG() and LEAD() window functions work, and what problems do they solve?

Last updated 3 July 2026

  • LAG() reads a value from a previous row and LEAD() from a following row within an ordered window, without a self-join.

  • Syntax is LAG(expr, offset, default): offset defaults to 1, and default fills boundary rows. They require ORDER BY in OVER(), with optional PARTITION BY per group.

  • They solve period-over-period deltas, status transition or gap detection, and durations between consecutive events, more simply and faster than self-joins or correlated subqueries.

  • https://medium.com/@harsh1995hg/sql-lag-and-lead-functions-unlocking-powerful-time-series-comparisons-in-your-data-430acb406597
  • https://www.sqlservercentral.com/articles/sql-window-functions-series-lag-and-lead
  • https://reintech.io/blog/sql-lead-lag-functions-complete-guide
  • https://www.youtube.com/watch?v=nHEEyX_yDvo
  • https://www.varsitytutors.com/practice/subjects/sql/lessons/lag-lead
  • https://learn.microsoft.com/en-us/sql/t-sql/functions/lag-transact-sql?view=sql-server-ver17
  • https://www.postgresql.org/docs/current/functions-window.html
  • https://learnsql.com/blog/sql-lag-function/
All SQL interview questions