How do LAG() and LEAD() window functions work, and what problems do they solve?
Last updated
LAG()reads a value from a previous row andLEAD()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 requireORDER BYinOVER(), with optionalPARTITION BYper 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/