LAG() OVER ...
All functions > WINDOW FUNCTION > LAG() OVER ...
Returns the value from the row that lags (precedes) the current row by a specified offset within the result set partition.
Syntax
LAG(expr [, offset [, default_value]]) OVER ([PARTITION BY expr [, ...]] [ORDER BY sort_item [, ...]] [ROWS|RANGE|GROUPS frame])
Notes
- Accesses data from a previous row in the same result set
- First expression is the value to return
- Second expression (optional) is the offset (number of rows backward, default 1)
- Third expression (optional) is the default value if offset exceeds partition bounds
- Requires ORDER BY inside OVER so the previous row is well-defined
- Useful for comparing current row with previous rows or calculating deltas
See also
Examples
FeatureQL
SELECT
f1 := ZIP(ARRAY[1,2,3] AS id, ARRAY[30,10,20] AS v).TRANSFORM(SELECT LAG(v, 1) OVER (ORDER BY id ASC)).UNWRAP() -- Previous row value along id order (v permuted so the result is not a sorted copy of v)
;Result
| f1 ARRAY |
|---|
| [null, 30, 10] |