LAG
window analytic
What changes
- Input
- ordered rows of the partition (frame for FIRST_VALUE/LAST_VALUE; offset rows for LAG/LEAD)
- Output or change
- one value per row
- Return type
- The data type of the specified scalar_expression. NULL is returned if scalar_expression is nullable or default is set to NULL.
Syntax at a glance
LAG (scalar_expression [ , offset ] [ , default ] ) [ IGNORE NULLS | RESPECT NULLS ] OVER ( [ partition_by_clause ] order_by_clause )
Work example
Compare a row with the prior value in a time or sequence order.
Set a complete partition and ordering rule, then decide what the first row should show.
Check your work LAG reads a prior row in the window order and returns null when that row is absent unless a default is supplied.
Practice SQL
Open in SQL FlowSELECT n, LAG(n) OVER (ORDER BY n) AS prior_n FROM (VALUES (10), (20), (30)) AS v(n);
Open Microsoft Learn for full syntax, permissions, and details for your version.