LAG, LEAD, FIRST_VALUE, and LAST_VALUE are offset window functions — they access a different row's value within the current partition rather than computing an aggregate across all rows. LAG looks backward (the previous row's value), LEAD looks forward (the next row's value), FIRST_VALUE returns the first row's value in the partition, and LAST_VALUE returns the last row's value. These functions are the SQL-native solution for period-over-period comparisons, streak detection, and boundary-value extraction — patterns that appear in virtually every time-series and event-sequence analysis.
Without offset functions, comparing a player's current innings score to their previous innings score required a self-join — joining the innings table to itself on player_id with a condition that selected the previous innings. Self-joins for sequence analysis are verbose, error-prone, and scale poorly because they produce an intermediate Cartesian product that must be filtered down. LAG and LEAD replace self-joins with a single, readable function call that executes in one linear pass over the sorted partition.
For data engineers, these functions are essential for incremental pipeline logic. Detecting whether a record represents a change from its predecessor (LAG), identifying the start and end boundaries of a dimension's validity period (LEAD for effective-to date in SCD Type 2), computing inter-event time deltas for session analysis, and extracting opening and closing values for daily OHLC financial metrics all rely on offset window functions. Mastering their frame specification and NULL handling removes the most complex correlated subquery patterns from pipeline transformation code.