Skip to main content
Version: current [25.x]

Categories: Window

LAG

Returns the row before the current one in a partition based on the ORDER BY clause without the need for a self-join. If there are no rows, this function returns NULL.

Syntax

LAG(expression, [offset]) OVER ([PARTITION BY partition_expression] [ORDER BY order_expression]) → same as input type

  • expression (optional): An expression that is returned.
  • offset (optional): The number of rows before the current row from which to obtain a value.

Examples

LAG example
SELECT "Category", 
"Descript",
"DayOfWeek",
LAG(DayOfWeek, 3)
OVER (
PARTITION BY "Category"
ORDER BY "DayOfWeek")
FROM Samples."samples.dremio.com"."SF_incidents2016.json"
-- Category, Descript, DayOfWeek, EXPR$3
-- ARSON, ARSON, Friday, null
-- ARSON, ARSON, Friday, null
-- ARSON, ARSON OF AN INHABITED DWELLING, Friday, null
-- ARSON, ARSON, Friday, Friday
LAG example
SELECT "Category", 
"Descript",
"DayOfWeek",
LAG(DayOfWeek)
OVER (
PARTITION BY "Category"
ORDER BY "DayOfWeek")
FROM Samples."samples.dremio.com"."SF_incidents2016.json"
-- Category, Descript, DayOfWeek, EXPR$3
-- ARSON, ARSON, Friday, null
-- ARSON, ARSON, Friday, Friday