Skip to main content

Categories: Window

LAG

Returns the value of the expression from the row that is offset rows before the current row within the partition. Returns NULL if there is no such row. The default offset is 1.

Syntax​

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

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

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
Return the value from the previous row
SELECT name,
LAG(name)
OVER (
ORDER BY val)
FROM (VALUES ('Dremio', 10), ('Cloud', 20), ('Lake', 30)) AS t(name, val)
-- name, EXPR$1
-- Dremio, null
-- Cloud, Dremio
-- Lake, Cloud
Compare LAG and LEAD
SELECT name,
LAG(name)
OVER (
ORDER BY val),
LEAD(name)
OVER (
ORDER BY val)
FROM (VALUES ('Dremio', 10), ('Cloud', 20), ('Lake', 30)) AS t(name, val)
-- name, EXPR$1, EXPR$2
-- Dremio, null, Cloud
-- Cloud, Dremio, Lake
-- Lake, Cloud, null