- Categories:
Window function syntax and usage (Ranking)
LAG¶
Accesses data in a previous row in the same result set without having to join the table to itself.
- See also:
Syntax¶
Arguments¶
exprThe expression to be returned based on the specified offset.
offsetThe number of rows backward from the current row from which to obtain a value. For example, an
offsetof 2 returns theexprvalue with an interval of 2 rows.Note that setting a negative offset has the same effect as using the LEAD function.
Default is 1.
defaultThe expression to return when the offset goes out of the bounds of the window. Supports any expression whose type is compatible with
expr.Default is NULL.
{ IGNORE | RESPECT } NULLSWhether to ignore or respect NULL values when an
exprcontains NULL values:IGNORE NULLSexcludes any row whose expression evaluates to NULL when offset rows are counted.RESPECT NULLSincludes any row whose expression evaluates to NULL when offset rows are counted.
Default:
RESPECT NULLS
Usage notes¶
The PARTITION BY clause partitions the result set produced by the FROM clause into partitions to which the function is applied. For more information, see Window function syntax and usage.
The ORDER BY clause orders the data within each partition.
Examples¶
Create the table and load the data:
This query shows the difference between this year’s revenue and the previous year’s revenue:
Create another table and load the data:
This query shows how the IGNORE NULLS clause affects the output. All rows (except the first) contain non-NULL values even if the preceding row contained NULL. If the preceding row contained NULL, then the current row uses the most recent non-NULL value.